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

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

问题描述

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

All the documentation I've found so far is to update keys that are already created:

 arr['key'] = val;

我有一个这样的字符串:"名称 = 奥斯卡 "

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']);

会弹出一个包含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屋!

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