重命名javascript数组中的键

1 javascript arrays key

假设我想将密钥"c3"更改为变量x ="b2"并保留密钥本身的值,因此它应如下所示:"b2":"example3".

var x = {
                "a1": "example1",
                "b2": "example2",
                "c3": "example3"
        };
Run Code Online (Sandbox Code Playgroud)

此外,是否有"更好"的数组类型,这将通过这个数组中的所有键完全正确

for(var a in x)循环?

jfr*_*d00 7

您无法更改javascript对象中键的值.相反,您可以分配新密钥,然后删除先前的密钥:

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"];
Run Code Online (Sandbox Code Playgroud)

并且,请理解这些不是数组.这些是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]]);
}
Run Code Online (Sandbox Code Playgroud)