gpt4 book ai didi

javascript - 为什么JS总是返回 'Cannot read property ' Push'of undefined'?

转载 作者:行者123 更新时间:2023-12-01 00:32:49 24 4
gpt4 key购买 nike

好吧,我看到了这个问题的解决方案,但我不清楚为什么它对我不起作用?我使用socket.io

//这是房间

var rooms = {
"1": [],
"2": [],
"3": [],
"4": [],
"5": []
};

这是监听者

socket.on('joinRoom', function (data) {

}

为什么

rooms[1].push(1); // work?

为什么

rooms["1"].push(1); // work?

为什么

rooms[data.room].push(1); // not work?

为什么

rooms["" + data.room].push(1) not work?    

为什么

rooms[data.room] = [];
rooms[data.room] = 1; // work?

data.room返回1;

最佳答案

即使条件不太清楚(特别是不知道data是什么),以下内容可能有效的唯一原因:

rooms[data.room] = [];
rooms[data.room] = 1;

同时这不会:

rooms[data.room].push(1);

data.room 返回的内容是否还不是 rooms 的键。

尝试执行此操作 rooms[data.room] = 1;,然后 console.log(rooms); 您很可能会找到 6 个 key ,而不是 5 个.

顺便说一句,当您设置 key /访问其值时,无需将 key 转换为字符串。它是自动转换的。它甚至可以转换对象(转换为字符串[object Object])。

关于javascript - 为什么JS总是返回 'Cannot read property ' Push'of undefined'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58364522/

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