我必须创建一个数组,其中的键(索引)在执行操作时将为strId (typeof strId is "string"),这样我在列表中会得到未定义的值,以下是代码。

var myRoomIdList = [];
var strId = "43457";

myRoomIdList[strId] = strId;

console.log(myRoomIdList);
console.log(myRoomIdList.length);

console.log(myRoomIdList);
Output: Undefined, undefiend, ......43457 times

console.log(myRoomIdList.length);
Output: 43457


请任何人能弄清楚为什么它会以这种方式运行。任何帮助将不胜感激。

最佳答案

[]数组专用于数字索引。您应该使用{}代替:

var myRoomIdList = {};

07-26 08:10