我试图将数字转换为字符串以用作键。但问题是,当我新转换的字符串时,它仍然像一个数字。有没有正确的方法呢?
JAVASCRIPT
var arr = [];
var num = 3;
var key = String(''+num); //Convert number into string
//var key = '' +num; //Tried this
//var key = num.toString(); //Tried this also
array[key] = true;
console.log(arr); //Returns [, , true]
console.log(arr.length); //Returns 3
基本上,我希望它只返回:
console.log(arr); //Return [true]
console.log(arr.length); //Return 1
答案 0 :(得分:3)
您要找的是对象({}
)而不是数组([]
)。请改用:
var obj = {};
var key = 3;
obj[key] = true; // no need to convert the key to string
示例:强>
var obj = {};
var key = 3;
obj[key] = true;
console.log(obj);