gpt4 book ai didi

javascript - 我应该如何理解 data.key 值始终未定义,但我可以使用 get set 或 change 等方法访问它

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:27 26 4
gpt4 key购买 nike

我简化了我的问题。在这段代码中

我尝试用谷歌搜索它,但我不知道如何调用它。

let data = () => {
let key = undefined;
let setKey = () => {
key = Math.floor( Math.random() * 6);
}
let getKey = () => {
return key;
}
let changeKey = (newKey) => {
key = newKey;
}
return {
key,
setKey,
getKey,
changeKey
}
}

let dataArray = []
for( let i = 0; i < 3; i++){
dataArray.push(data())
}
dataArray.forEach( data => {console.log(data.key)}) // **undefined**
dataArray.forEach( data => {console.log(data.getKey())}) // **undefined**
dataArray.forEach( data => {data.setKey()})
dataArray.forEach( data => {console.log(data.getKey())}) // **rundom numbers**
dataArray.forEach( data => {console.log(data.key)}) // **undefined**

dataArray.length = 0;
for( let i = 0; i < 3; i++){
dataArray.push(data())
}
dataArray.forEach( data => {console.log(data.getKey())}) // **uff -> undefined**

是的,所以我希望这很清楚我的理解问题在哪里。可能是我对JS的一般理解有问题。我希望你能帮助我。

最佳答案

整数未被引用,它立即用作值。在调用 return 语句的那一刻,您的 key 的值(未定义)被复制到您返回到 key 子对象中的对象(仍未定义)。

函数体内的key和返回的key是两个不同的对象。

我还添加了对象示例,因为对象值也被复制,但对象实际值是引用,而不是对象本身。

let data = () => {
let key = undefined;
let ourObject = {};
let setKey = () => {
key = Math.floor( Math.random() * 6);
ourObject.key = key;
}
let getKey = () => {
return key;
}
let getOurObject = () => { return ourObject; }
let changeKey = (newKey) => {
key = newKey;
}
return {
key,
setKey,
getKey,
changeKey,
ourObject,
getOurObject
}
}

let ourData = data();
console.log('Should be undefined', ourData.key)
console.log('Still undefined', ourData.getKey())
ourData.setKey();
console.log('Now the value', ourData.getKey())
console.log('int is used by value directly, so it has the value it had when you executed data() and what was in return object at that time', ourData.key)
console.log('However objects are not used directly, their reference is copied and therefore through same reference you can get to the object', ourData.ourObject)
ourData.ourObject = null;
console.log('Still the ourObject variable itself is different than the one returned', ourData.ourObject)
console.log('This is reason the variable was nulled, but object still exist', ourData.getOurObject())

关于javascript - 我应该如何理解 data.key 值始终未定义,但我可以使用 get set 或 change 等方法访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491656/

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