status_name=Array("a","b","c","b","e","f");
status_id=Array( 1, 2, 3, 4, 5, 6);
如何组合这两个数组并构建多维数组预期的多维数组就像这样
[["a", 1],["b", 2],["c", 3],["d", 4],["e", 5],["f", 6]]
帮助我如何使用上面两个数组值并构建我期望的多维数组
答案 0 :(得分:7)
由于你包含了jQuery,你可以使用jQuery.map
与Linus的回答类似:
var result = [],
status_name = ["a","b","c","b","e","f"],
status_id = [1, 2, 3, 4, 5, 6];
result = $.map(status_name, function (el, idx) {
return [[el, status_id[idx]]];
});
看看你的变量名,我猜你是来自一种语言(比如PHP)。如果是这种情况,请确保记住使用var
关键字声明局部变量,否则您将污染全局范围,并且您将在IE中遇到一些可怕的错误。
答案 1 :(得分:5)
JavaScript没有buitin方法,但您可以自己轻松编写:
function zip(arrayA, arrayB) {
var length = Math.min(arrayA.length, arrayB.length);
var result = [];
for (var n = 0; n < length; n++) {
result.push([arrayA[n], arrayB[n]]);
}
return result;
}
选择名称zip
是因为执行此类操作的函数通常在其他语言中称为zip
。
答案 2 :(得分:1)
var combined = [], length = Math.min(status_name.length, status_id.length);
for(var i = 0; i < length; i++) {
combined.push([status_name[i], status_id[i]]);
}
您也可以使用Array.prototype.map,但并非所有浏览器都支持:
var combined = status_name.map(function(name, index) { return [name, status_id[index]] });
答案 3 :(得分:1)
我尝试了自己,并提出了这个解决方案,这可能对某人有所帮助
status_name=Array("a","b","c","b","e","f");
status_id=Array( 1, 2, 3, 4, 5, 6);
脚本:
Values=[];
for (i = 0; i < status_name.length; ++i)
{
Values[i] =Array(status_name[i], status_id[i]);
}
答案 4 :(得分:0)
试
function array_combine (keys, values) {
// Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values
//
// version: 1102.614
// discuss at: http://phpjs.org/functions/array_combine
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: array_combine([0,1,2], ['kevin','van','zonneveld']);
// * returns 1: {0: 'kevin', 1: 'van', 2: 'zonneveld'}
var new_array = {},
keycount = keys && keys.length,
i = 0;
// input sanitation
if (typeof keys !== 'object' || typeof values !== 'object' || // Only accept arrays or array-like objects
typeof keycount !== 'number' || typeof values.length !== 'number' || !keycount) { // Require arrays to have a count
return false;
}
// number of elements does not match
if (keycount != values.length) {
return false;
}
for (i = 0; i < keycount; i++) {
new_array[keys[i]] = values[i];
}
return new_array;
参考
- arr combine
- array combine
答案 5 :(得分:0)
var status_name = ["a","b","c","b","e","f"],
status_id = [1,2,3,4,5,6],
r = [];
r = $.map(status_name, function(n, i) {
return [[n, status_id[i]]];
});
请注意return [[n, status_id[i]]]
和return [n, status_id[i]]
之间的区别。使用前者将产生2d数组,而使用后者将产生1d数组。