js奇怪的行为数组解构
js strange behavior Array Destructuring
const test = () => {
const arr = [1, 2]
console.log("any strings") // focus on this line
[arr[0], arr[1]] = [arr[1], arr[0]]
}
const test1 = () => {
const arr = [1, 2]
console.log("any strings"); // add a semicolon will works or comment this line will works too
[arr[0], arr[1]] = [arr[1], arr[0]]
}
test() // error
test1() // works
为什么第一个函数测试抛出错误"Cannot set property '2' of undefined"?
这里的问题与解构无关。在第一个片段中,因为 console.log
之后的第二行以左括号开头,所以它认为这些行是同一语句的一部分。
console.log("any strings")[arr[0], arr[1]]
请注意,在括号表示法中,[arr[0], arr[1]]
将解析为 [arr[1]]
- 这是逗号运算符。因此,它试图将调用 console.log("any strings")
的结果分配给 [arr[1]]
= [2]
属性。对于解释器来说,它与这个片段相同:
const test = () => {
const arr = [1,2]
console.log("any strings")[arr[0], arr[1]]
= [arr[1], arr[0]]
}
test()
同于:
const test = () => {
const arr = [1,2]
console.log("any strings")[arr[1]]
= [arr[1], arr[0]]
}
test()
当然console.log
returnsundefined
;它没有这样的 属性 [2]。有疑问时始终使用分号。
const test = () => {
const arr = [1, 2]
console.log("any strings") // focus on this line
[arr[0], arr[1]] = [arr[1], arr[0]]
}
const test1 = () => {
const arr = [1, 2]
console.log("any strings"); // add a semicolon will works or comment this line will works too
[arr[0], arr[1]] = [arr[1], arr[0]]
}
test() // error
test1() // works
为什么第一个函数测试抛出错误"Cannot set property '2' of undefined"?
这里的问题与解构无关。在第一个片段中,因为 console.log
之后的第二行以左括号开头,所以它认为这些行是同一语句的一部分。
console.log("any strings")[arr[0], arr[1]]
请注意,在括号表示法中,[arr[0], arr[1]]
将解析为 [arr[1]]
- 这是逗号运算符。因此,它试图将调用 console.log("any strings")
的结果分配给 [arr[1]]
= [2]
属性。对于解释器来说,它与这个片段相同:
const test = () => {
const arr = [1,2]
console.log("any strings")[arr[0], arr[1]]
= [arr[1], arr[0]]
}
test()
同于:
const test = () => {
const arr = [1,2]
console.log("any strings")[arr[1]]
= [arr[1], arr[0]]
}
test()
当然console.log
returnsundefined
;它没有这样的 属性 [2]。有疑问时始终使用分号。