gpt4 book ai didi

javascript - 为什么这些 JavaScript 代码片段虽然都遇到了错误,但表现却不同?

转载 作者:IT王子 更新时间:2023-10-29 02:41:01 24 4
gpt4 key购买 nike

var a = {}
var b = {}

try{
a.x.y = b.e = 1 // Uncaught TypeError: Cannot set property 'y' of undefined
} catch(err) {
console.error(err);
}
console.log(b.e) // 1

var a = {}
var b = {}

try {
a.x.y.z = b.e = 1 // Uncaught TypeError: Cannot read property 'y' of undefined
} catch(err) {
console.error(err);
}

console.log(b.e) // undefined

最佳答案

实际上,如果您正确阅读错误消息,情况 1 和情况 2 会抛出不同的错误。

案例a.x.y:

Cannot set property 'y' of undefined

大小写 a.x.y.z:

Cannot read property 'y' of undefined

我想最好用通俗易懂的英文来描述step-by-step execution。

案例一

// 1. Declare variable `a`
// 2. Define variable `a` as {}
var a = {}

// 1. Declare variable `b`
// 2. Define variable `b` as {}
var b = {}

try {

/**
* 1. Read `a`, gets {}
* 2. Read `a.x`, gets undefined
* 3. Read `b`, gets {}
* 4. Set `b.z` to 1, returns 1
* 5. Set `a.x.y` to return value of `b.z = 1`
* 6. Throws "Cannot **set** property 'y' of undefined"
*/
a.x.y = b.z = 1

} catch(e){
console.error(e.message)
} finally {
console.log(b.z)
}

案例二

// 1. Declare variable `a`
// 2. Define variable `a` as {}
var a = {}

// 1. Declare variable `b`
// 2. Define variable `b` as {}
var b = {}

try {

/**
* 1. Read `a`, gets {}
* 2. Read `a.x`, gets undefined
* 3. Read `a.x.y`, throws "Cannot **read** property 'y' of undefined".
*/
a.x.y.z = b.z = 1

} catch(e){
console.error(e.message)
} finally {
console.log(b.z)
}

在评论中,Solomon Tam找到 this ECMA documentation about assignment operation .

关于javascript - 为什么这些 JavaScript 代码片段虽然都遇到了错误,但表现却不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com