如何在javascript关联数组中动态创建键?
到目前为止,我发现的所有文档都是更新已创建的密钥:
arr['key'] = val;
我有一个像" name = oscar "
我想最终得到这样的东西:
{ name: 'whatever' }
那就是我拆分字符串并获取第一个元素,我想把它放在字典中。
var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // prints nothing.
答案 0 :(得分:483)
不知怎的,所有例子虽然运作良好,但过于复杂:
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 ;-)
}
答案 1 :(得分:140)
使用第一个示例。如果密钥不存在,则会添加。
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]] );
答案 2 :(得分:29)
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.
答案 3 :(得分:9)
作为对MK_Dev的回应,一个人能够迭代,但不能连续。(显然需要一个数组)
快速谷歌搜索显示hash tables in 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]);
}
答案 4 :(得分:4)
原始代码(我添加了行号,因此可以参考它们):
1 var text = ' name = oscar '
2 var dict = new Array();
3 var keyValuePair = text.split(' = ');
4 dict[ keyValuePair[0] ] = 'whatever';
5 alert( dict ); // prints nothing.
差不多......
trim
,因此它是name = oscar
。trim
,使用=
并修剪每个keyValuePair 在3之后和4之前添加一行:
key = keyValuePair[0];`
第4行:现在变为:
dict[key] = keyValuePair[1];
第5行:转到:
alert( dict['name'] ); // it will print out 'oscar'
我想说的是dict[keyValuePair[0]]
不起作用,您需要将字符串设置为keyValuePair[0]
并将其用作关联键。这是我让我工作的唯一方法。设置完成后,您可以使用数字索引或键入引号来引用它。
希望有所帮助。
答案 5 :(得分:3)
所有现代浏览器都支持Map,这是键/值数据限制。使用Map优于Object的原因有几个:
- 一个对象有一个原型,因此地图中有默认键。
- 对象的键是字符串,它们可以是Map的任何值。
- 您可以轻松获取地图的大小,同时必须跟踪对象的大小。
示例:
var myMap = new Map();
var keyObj = {},
keyFunc = function () {},
keyString = "a string";
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");
myMap.size; // 3
myMap.get(keyString); // "value associated with 'a string'"
myMap.get(keyObj); // "value associated with keyObj"
myMap.get(keyFunc); // "value associated with keyFunc"
如果您希望将未从其他对象引用的密钥进行垃圾回收,请考虑使用WeakMap而不是Map。
答案 6 :(得分:3)
我认为如果你刚刚创建这样的
会更好var arr = [];
arr = {
key1: 'value1',
key2:'value2'
};
了解更多信息,请看一下
答案 7 :(得分:1)
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]);
}
这没关系,但迭代遍历数组对象的每个属性。 如果你只想遍历属性myArray.one,myArray.two ...你试试这样
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(i=0;i<maArray.length;i++{
console.log(myArray[myArray[i]])
}
现在你可以通过myArray [“one”]访问它们并仅通过这些属性进行迭代。
答案 8 :(得分:1)
var obj = {};
for (i = 0; i < data.length; i++) {
if(i%2==0) {
var left = data[i].substring(data[i].indexOf('.') + 1);
var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);
obj[left] = right;
count++;
}
}
console.log("obj");
console.log(obj);
// show the values stored
for (var i in obj) {
console.log('key is: ' + i + ', value is: ' + obj[i]);
}
}
};
}