当前位置:  开发笔记 > 编程语言 > 正文

在JavaScript关联数组中动态创建键

如何解决《在JavaScript关联数组中动态创建键》经验,为你挑选了4个好方法。



1> Eugene Lazut..:

不知何故,所有示例虽然运作良好,但过于复杂:

他们使用new Array(),这是一个简单的关联数组(AKA字典)的过度杀伤(和开销).

更好的用途new Object().工作正常,但为什么所有这些额外打字?

这个问题被标记为"初学者",所以让我们简单一点.

在JavaScript中使用字典或"为什么JavaScript没有特殊的字典对象?"的超级简单方法:

// create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // huh? {} is a shortcut for "new Object()"

// add a key named fred with value 42
dict.fred = 42;  // we can do that because "fred" is a constant
                 // and conforms to id rules

// add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // we use the subscript notation because
                           // the key is arbitrary (not id)

// add an arbitrary dynamic key with a dynamic value
var key = ..., // insanely complex calculations for the key
    val = ...; // insanely complex calculations for the value
dict[key] = val;

// read value of "fred"
val = dict.fred;

// read value of 2bob2
val = dict["2bob2"];

// read value of our cool secret key
val = dict[key];

现在让我们改变价值观:

// change the value of fred
dict.fred = "astra";
// the assignment creates and/or replaces key-value pairs

// change value of 2bob2
dict["2bob2"] = [1, 2, 3];  // any legal value can be used

// change value of our secret key
dict[key] = undefined;
// contrary to popular beliefs assigning "undefined" does not remove the key

// go over all keys and values in our dictionary
for (key in dict) {
  // for-in loop goes over all properties including inherited properties
  // let's use only our own properties
  if (dict.hasOwnProperty(key)) {
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

删除值也很容易:

// let's delete fred
delete dict.fred;
// fred is removed, the rest is still intact

// let's delete 2bob2
delete dict["2bob2"];

// let's delete our secret key
delete dict[key];

// now dict is empty

// let's replace it, recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // we can't add the original secret key because it was dynamic,
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// let's rename temp1 into our secret key:
if (key != "temp1") {
  dict[key] = dict.temp1; // copy the value
  delete dict.temp1;      // kill the old key
} else {
  // do nothing, we are good ;-)
}


这看起来像Sheldon Cooper的答案:)
完美的完整答案,应该是默认的
但是,"我们无法添加原始密钥,因为它是动态的"本身并不正确,即使您不能在{}中直接使用变量作为密钥,也不能使用带点符号的密钥.我们仍然可以通过"dict [key] = val"添加动态密钥,如示例中的早期所示.限制是使用{} -notation而不是键本身.
您好,我知道我回答的是旧答案,但它在Google上排名很高,所以无论如何我都会问.我有点困惑于"我们无法添加原始密钥,因为它是动态的,我们只能添加静态密钥"在您的示例中意味着.

2> tvanfosson..:

使用第一个示例.如果该密钥不存在,则将添加该密钥.

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

将弹出一个包含'oscar'的消息框.

尝试:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );


更好的是使用Object(括号{}表示法)来避免包含在Array原型中的.length,.slice()等的开销
请参阅Danny的更完整的解释.您将无法在带索引的for循环中引用数组值(例如myarray [i]).希望这不会太混乱.

3> Orion Edward..:

Javascript 没有关联数组,它有对象.

以下代码行完全相同 - 将对象上的'name'字段设置为'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

看起来你有一个关联数组,因为Array它也是一个Object- 但是你实际上并没有在数组中添加东西,而是在对象上设置字段.

现在已经解决了这个问题,这是一个有效的解决方案

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// split into key and value
var kvp = cleaned.split('=');

// put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // prints oscar.



4> Danny..:

响应MK_Dev,可以迭代,但不能连续.(显然需要一个数组)

快速谷歌搜索在javascript中显示哈希表

用于循环散列中的值的示例代码(来自上述链接):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

推荐阅读
个性2402852463
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有