在JavaScript关联数组中动态创建键
问题描述:
如何在javascript关联数组中动态创建键?
How can I dynamically create keys in javascript associative arrays?
到目前为止,我发现的所有文档都是更新已创建的密钥:
All the documentation I've found so far is to update keys that are already created:
arr['key'] = val;
我有一个像这样的字符串name = oscar
I have a string like this " name = oscar "
我想最终得到这样的结果:
And I want to end up with something like this:
{ name: 'whatever' }
这是我拆分字符串并获取第一个元素,我想把它放在字典里。
That is I split the string and get the first element, and I want to put that in a dictionary.
var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // prints nothing.
答
使用第一个示例。如果密钥不存在,则会添加。
Use the first example. If the key doesn't exist it will be added.
var a = new Array();
a['name'] = 'oscar';
alert(a['name']);
将弹出一个包含'oscar'的消息框。
Will pop up a message box containing 'oscar'.
尝试:
var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );