在JavaScript关联数组中动态创建键 [英] Dynamically creating keys in a JavaScript associative array

查看:112
本文介绍了在JavaScript关联数组中动态创建键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我发现的所有文档都是更新已经创建的密钥:

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, split the string and get the first element, and then 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']);

将弹出一个包含奥斯卡"的消息框.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆