简体   繁体   English

在JavaScript中组合两个数组

[英]Combine two arrays in JavaScript

Can I merge two arrays in JavaScript like this? 我可以像这样在JavaScript中合并两个数组吗?

these arrays: 这些数组:

arr1 = ['one','two','three'];
arr2 = [1,2,3];

into

arr3 = ['one': 1, 'two': 2, 'three' : 3]
var arr3 = {};
for (var i = 0; i < arr1.length; i++) {
    arr3[arr1[i]] = arr2[i];
}

Please note that arr3 is not array, it is object . 请注意, arr3不是数组,它是对象

You can use Array.prototype.reduce ... 你可以使用Array.prototype.reduce ...

var arr3 = arr1.reduce(function(obj, val, i) {
    obj[val] = arr2[i];
    return obj;
}, {});

DEMO: http://jsfiddle.net/GMxcM/ 演示: http //jsfiddle.net/GMxcM/

{
    "one": 1,
    "two": 2,
    "three": 3
}

Just because you said in jQuery , here's a jQuery $.each version. 只是因为你in jQuery说过,这里是一个jQuery $.each版本。

arr1 = ['one','two','three'];
arr2 = [1,2,3];
arr3 = {};
$.each(arr1, function(i, value){
  arr3[value] = arr2[i];
});
console.log(JSON.stringify(arr3));

output -> 输出 - >

{"one":1,"two":2,"three":3}

here's a working jsFiddle 这是一个有效的jsFiddle

Loop! 环!

var arr1 = ['one','two','three'];
var arr2 = [1,2,3];
var result = {};

for(var i = 0; i < arr1.length; i++) {
    result[arr1[i]] = arr2[i];
}

更简单:

$.merge(arr1, arr2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM