假设我想将键“c3”更改为变量 x =“b2”并保留键本身的值,因此它应该如下所示:“b2”:“example3”。
var x = {
"a1": "example1",
"b2": "example2",
"c3": "example3"
};
此外,是否有“更好”类型的数组,可以遍历此数组中的所有键 一个
for ( var a in x ) 循环?
最佳答案
您不能更改 javascript 对象中键的值。相反,您可以分配一个新 key ,然后删除之前的 key :
var x = {
"a1": "example1",
"b2": "example2",
"c3": "example3"
};
// assign new key with value of prior key
x["a2"] = x["a1"];
// remove prior key
delete x["a1"];
而且,请理解这些不是数组。这些是 Javascript 对象。数组是一种不同类型的数据结构。
语法 for (var key in x)
是迭代对象属性的常用方法。以下是几种不同方法的总结:
// iterate all enumerable properties, including any on the prototype
for (var key in x) {
console.log(key +", " + x[key]);
}
// iterate all enumerable properties, directly on the object (not on the prototype)
for (var key in x) {
if (x.hasOwnProperty(key)) {
console.log(key +", " + x[key]);
}
}
// get an array of the keys and enumerate that
var keys = Object.keys(x);
for (var i = 0; i < keys.length; i++) {
console.log(keys[i] +", " + x[keys[i]]);
}
关于javascript - 重命名javascript数组中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27158371/