我怎么能动态创建键在javascript associative arrays?

所有的文档我发现迄今为止是更新项已经建立:

 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.
有帮助吗?

解决方案

使用第一个例子。如果该键不存在,它将被添加。

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

会弹出含有“奥斯卡”的消息框。

尝试:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );

其他提示

不知何故,所有的实例,同时工作,是过于复杂:

  • 他们使用 new Array(), ,这是一个矫枉过正(和开销),为一个简单的关联阵列(又名字典)。
  • 更好的使用 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 ;-)
}

的Javascript 不具有关联数组,它具有的对象

的下面几行代码都做同样的事情。 - 设置“名称”中的一个目的是“猎户”上

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.

在响应于MK_Dev,一个能够进行迭代,但不连续。(对于明显需要一种阵列)

快速谷歌搜索带来了哈希表

用于在散列上循环值的示例代码(从上述链路):

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

原始代码(I增加的线号码,以便可以参照它们):

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.

几乎没有...

  • 第1行:你应该做的 trim 上文所以它是 name = oscar.
  • 第3行:好吧只要你永远有空间围绕你的平等。可能最好不要 trim 在第1行中,使用 = 和修剪每型
  • 增加一个行之后3和4之前:

    key = keyValuePair[0];`
    
  • 4行:现在变成:

    dict[key] = keyValuePair[1];
    
  • 第5行:更改为:

    alert( dict['name'] );  // it will print out 'oscar'
    

我想说的是, dict[keyValuePair[0]] 不起作用,需要设置一个字符串 keyValuePair[0] 和使用,作为关联的关键。这是唯一的方式我有我的工作。之后你必须设置这个你可以把它与指数数字或者关键在报价。

希望这有所帮助。

所有现代化的支持的浏览器 地图, ,这是一个关键/价值的数据狭窄。有几个原因,使用地图的比对象:

  • 一个对象有一个原型,所以有默认的钥匙在地图。
  • 钥匙的对象是串,他们在那里可以是任何价值的地图。
  • 你可以获得大小的地图很容易的话,你必须跟踪的尺寸的对象。

例如:

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 而不是个地图。

我觉得这是更好,如果你只是喜欢这个创建

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

有关的详细信息,看看这

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

这是确定的,但访问过的每一个酒店的阵列的对象。如果你只想迭代过性myArray.一、myArray.两个...你尝试这样

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["一个"]和迭代,只有通过这些属性。

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

            }
        };

}

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top