我有一个小示例来定义并分配给 arr
数组。
var arr;
if (arr = [1]) { // arr is an array here, it contains 1 element
console.log(arr.length); // 1
}
然后,我想获取数组的长度
var arr;
// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
console.log(arr.length);
}
Uncaught TypeError: Cannot read property 'length' of undefined
最佳答案
var arr;
// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
console.log(arr.length);
}
由于operator precedence而失败。 &&
的优先级高于赋值 =
,因此首先对其求值。
[1] && arr.length
表达式由数组文字和 arr.length
表达式组成。并且 arr.length
失败,因为 arr
此时未定义。
引用文献:
关于javascript - 在 if 语句中获取/设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448884/