NodeJs Express 框架应用程序中 Jade 模板中的字符串比较问题

String comparison issue in Jade Template in NodeJs Express framework application

我在我的 NodeJs (Express Framework) 应用程序中比较 Jade 模板中的两个变量。 我可以看到值相同但不确定为什么它不起作用。 下面是一段代码。

select#corpid.form-control.grid-select(name='corpid', style='display: none', value='#{ScheduleList.CorpId}', onchange="setEmployer(this)")
    each item in Employers
        if(new String(item.EmployerId) == new String(ScheduleList.ProdEmployerId))
            option(value = '#{item.EmployerId}', selected='selected') #{item.AccountName}
        else
            option(value = '#{item.EmployerId}', eid="#{new String(item.EmployerId)}", pid="#{new String(ScheduleList.ProdEmployerId)}") #{item.AccountName}

你可以在上面看到,我显示了两个 id,id=101 是一样的,但它仍然没有根据 if[= 添加 selected 属性20=]块。

您正在测试字符串与 new String(...) == new String(...) 的相等性,这不是正确的方法。 您实际上是在比较绝对不相同的 String objects 。为了正确比较两个字符串,您必须使用 new String(item.EmployerId).valueOf() === new String(ScheduleList.ProdEmployerId).valueOf()String(item.EmployerId) === String(ScheduleList.ProdEmployerId) 作为 String() 将对象转换为原始字符串。

var s_prim = 'foo'; var s_obj = new String(s_prim);

console.log(typeof s_prim); // 日志 "string" console.log(typeof s_obj); // 日志 "object"

当 == 时,字符串基元和字符串对象也会给出不同的结果 一个简单的 运行 像新的一样 字符串('a') == 新字符串('a') 将证明这一点,使用 s_obj .valueOf() 转换为原始数据,它会起作用