[英]How can I use number as key?
I have ids like as numbers 374,242,435我有像数字 374,242,435 这样的 ID
I want to use this as key of hash for the object.我想用它作为对象的哈希键。
var json = [];
ids = [374,242,435];
for(let i in ids) {
var id = ids[i];
json[id] = []; // it makes 372 array!!!
json[id]['name'] = name;
json[id]['color'] = color;
}
Can I make object using number as key????我可以使用数字作为键来制作对象吗????
This is my silly mistake这是我的愚蠢错误
I just changed var json = [];
我刚刚改变了
var json = [];
-> var json = {};
->
var json = {};
it works.有用。
and thank you for your comments.并感谢您的评论。
let json = {};
let ids = [374,242,435];
for(let i in ids) {
let id = ids[i];
json[id] = {
name: 'some name',
color: '#ff0000'
};
}
EDIT: A better version编辑:更好的版本
let json = {};
let ids = [374,242,435];
ids.forEach((id) => {
json[id] = {
name: 'some name',
color: '#ff0000'
};
});
You can use Map to store key-value pair.您可以使用 Map 来存储键值对。 In Map, key will not just be string.
在 Map 中,key 不仅仅是字符串。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var json = {};
var ids = [374,242,435];
for(const i of ids) {
json[i] : {
name : 'name',
color : '#colorcode'
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.