我有一个对象数组,并且属性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) { ... }
}
由于第一个代码总是转换,我不知道两个条件是否更好。