javascript 将数组转换为关联数组的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9465639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:45:49  来源:igfitidea点击:

Function to convert an Array to an Associative array

javascriptarraysassociative-array

提问by Murtaza Khursheed Hussain

Possible Duplicate:
Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?

可能的重复:
在 JavaScript 中将平面数组 [k1,v1,k2,v2] 转换为对象 {k1:v1,k2:v2}?

I want to convert an array to an associative array in JavaScript.

我想在 JavaScript 中将数组转换为关联数组。

For example, given the following input,

例如,给定以下输入,

  var a = ['a', 'b', 'c', 'd'];

I want to get the next associative array as output:

我想获得下一个关联数组作为输出:

  {'a' : 'b', 'c' : 'd'}

How can I do that?

我怎样才能做到这一点?

回答by Rob W

Using .forEach:

使用.forEach

var a = ['a', 'b', 'c', 'd'];
var obj_a = {};
a.forEach(function(val, i) {
    if (i % 2 === 1) return; // Skip all even elements (= odd indexes)
    obj_a[val] = a[i + 1];   // Assign the next element as a value of the object,
                             // using the current value as key
});
// Test output:
JSON.stringify(obj_a);       // {"a":"b","c":"d"}

回答by Rich O'Kelly

Try the following:

请尝试以下操作:

var obj = {};
for (var i = 0, length = a.length; i < length; i += 2) {
  obj[a[i]] = a[i+1];
}

回答by Willem Mulder

There is no such thing as an associative array, they're called Objects but do pretty much the same :-)

没有关联数组这样的东西,它们被称为Objects 但几乎相同:-)

Here's how you would do the conversion

以下是您将如何进行转换

 var obj = {}; // "associative array" or Object
 var a = ['a', 'b', 'c', 'd'];
 for(index in a) {
     if (index % 2 == 0) {
         var key = a[index];
         var val = a[index+1];
         obj[key] = val;
     }
 }