在JavaScript关联数组中动态创建键 [英] Dynamically creating keys in JavaScript associative array
本文介绍了在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]] );
这篇关于在JavaScript关联数组中动态创建键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文