我想通过检查 objects 属性在 JavaScript 中创建一个字典。
var item = {};
if(item.hasOwnProperty("xyz")){
//do wat is required
}else{
//add the key property to the item object
}
如何将这个“xyz”键属性添加到对象是我的问题。
谢谢
最佳答案
你只需要使用 item.xyz='Whatever'
并且 xyz
将被添加到 item
var item = {};
if (item.hasOwnProperty('xyz')) {
console.log('item has xyz');
} else {
item.xyz = 'something';
//item["xyz"] = 'something'; You can also use this
}
console.log(item);
关于javascript - 如果 Javascript 中不存在数组键,如何添加键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22829900/