我可以像这样在 JavaScript 中合并两个数组吗?
这些数组:
arr1 = ['one','two','three'];
arr2 = [1,2,3];
进入
arr3 = ['one': 1, 'two': 2, 'three' : 3]
我可以像这样在 JavaScript 中合并两个数组吗?
这些数组:
arr1 = ['one','two','three'];
arr2 = [1,2,3];
进入
arr3 = ['one': 1, 'two': 2, 'three' : 3]
var arr3 = {};
for (var i = 0; i < arr1.length; i++) {
arr3[arr1[i]] = arr2[i];
}
请注意,这arr3
不是数组,而是对象。
你可以使用Array.prototype.reduce
...
var arr3 = arr1.reduce(function(obj, val, i) {
obj[val] = arr2[i];
return obj;
}, {});
演示:http: //jsfiddle.net/GMxcM/
{
"one": 1,
"two": 2,
"three": 3
}
正因为你说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));
输出->
{"one":1,"two":2,"three":3}
环形!
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);