比较键对象与javascript和angularjs中的字符串值

时间:2018-08-03 08:13:01

标签: javascript angularjs angularjs-ng-repeat

我有一个名为datePrintable的变量,键objec表示该月的月份和数组值天:

{12:[18,19,20,21,22,23,24,25,26]}

在有角度的模板中,我有两个嵌套的ng-repeat指令,我这样运行:

ng-repeat="(month,days) in datesPrintable"
    ng-repeat="day in days track by $index"

在其中,我调用一个传递此变量的方法:

isDayAvailable(day, month);

在此函数中,我正在将month与另一个变量(称为myMonth)进行比较,以检查是否相等,而在chrome中,ie即无效,因为month是关键对象(我认为):

在控制台中,我打印以下内容:

var myMonth = '12';

console.log(myMonth); // 12
console.log(month); // 12
console.log(typeof myMonth); // string
console.log(typeof month); // string
console.log(month.length); // 2 in chrome; 3 in ie
console.log(month == myMonth); // true in chrome; false in ie;

有人可以帮我比较一下吗?我无法更改结构,因为它在很多地方都使用过。

3 个答案:

答案 0 :(得分:1)

如果在IE中您的month在尝试将其转换为int时返回NaN,则可能不是以空格开头。
您可以尝试使用与1或2位数字匹配的正则表达式提取数字部分(如果仅使用2位月份格式(前导0),则删除1,):

/\d{1,2}/

var month = "{12";

console.log("This should be 12: ", parseInt(" 12"))
console.log("This should be NaN: ", parseInt(month))

var regex = /\d{1,2}/;

var result = month.match(regex);
if (result){
  month = result[0];
  console.log(month)
  // now compare with myMonth
}

PS。请注意,在每个函数调用中创建正则表达式可能效率不高。最好一次创建并重复使用

答案 1 :(得分:0)

最好将月份号作为值而不是键。在javascript中,您应该与===进行比较,而不是==。尝试month.trim()您的变量,或将其解析为数字:parseInt()

答案 2 :(得分:0)

您可以使用三重等于进行比较。它同时比较值和类型,而'=='尝试将变量转换为相同类型以仅比较值。

12 == '12' //true
12 === '12' //false