javascript将int值解析为int

时间:2017-10-19 13:11:24

标签: javascript casting type-conversion conditional-statements

我有一个对象数组,并且属性id可能包含整数或字符串。我正在使用该属性进行比较,但现在我猜测是否总是将整数id转换为整数,即使它是一个整数,或者询问它是否为字符串然后转换它。我的意思是:

let myArray = [{id: 1, ...otherprops}, {id: 2, ...otherprops}, {id: '3', ...otherprops}, {id: '4', ...otherprops}];

这是否更有效......

for (let x of myArray) {
   if (parseInt(x.id, 10) === 3) {
      ...
   }
}

或者这段代码:

for (let x of myArray) {
   let id = -1;
   if (typeof x.id === 'string') {
      id = parseInt(x.id, 10);
   }
   if (id === 3) { ... }
}

由于第一个代码总是转换,我不知道两个条件是否更好。

1 个答案:

答案 0 :(得分:3)

如果您知道,您只有数字或数字,那么您可以unary plus +转换为数字,这不会改变数字。

var id = +x.id;