Javascript 更改 js 关联数组中的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6865233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change key in js associative array
提问by Matt R. Wilson
If I have:
如果我有:
var myArray = new Array();
myArray['hello'] = value;
How can I change the key 'hello' to something else?
如何将键 'hello' 更改为其他键?
Something like this would work.
像这样的事情会起作用。
var from = 'hello',
to = 'world',
i, value = myArray[from];
for( i in myArray )
if( i == from ) myArray.splice( i, 1 );
myArray[to] = value;
But is there a native function or a better way to do it?
但是是否有本机功能或更好的方法来做到这一点?
edit:
编辑:
Due to the lack of associative arrays in js, what I want to do modify the property name of an object as efficiently as possible.
由于js中缺少关联数组,我想做的就是尽可能高效地修改对象的属性名称。
回答by KARASZI István
In JavaScript there is no such thing as associative Array. Objects can be used instead:
在 JavaScript 中,没有关联数组这样的东西。可以使用对象代替:
var myHash = new Object();
or
或者
var myHash = {};
replace can be done like this:
替换可以这样完成:
myHash["from"] = "value";
myHash["to"] = myHash["from"];
delete myHash["from"];
but the preferred way to write it:
但首选的写法:
myHash.from = "value";
myHash.to = myHash.from;
delete myHash.from;
回答by Pointy
You can't really "change" the property name, but you can always assign a property value to a new name, and then delete the original one.
您无法真正“更改”属性名称,但您始终可以将属性值分配给新名称,然后删除原始名称。
myArray['world'] = myArray.hello;
delete myArray.hello;
Also, you're working with an Array instance but using it as a simple object; everything you're doing would work just as well with:
此外,您正在使用 Array 实例,但将其用作简单对象;您所做的一切都可以与:
var myArray = {};
The "splice()" you're attempting in the code posted won't work, because it's only for the actual integer-indexed array properties, and not the named properties.
您在发布的代码中尝试的“splice()”不起作用,因为它仅适用于实际的整数索引数组属性,而不适用于命名属性。
That "delete" doesn't really delete a property really doesn't matter. The "undefined" value is what you get when you check an object for a property and there's no such property.
那个“删除”并没有真正删除一个属性真的无关紧要。“未定义”值是您在检查对象的属性时得到的值,但没有这样的属性。