我有这个多个数组:
var array = [["par0_0","par0_1","par0_2"],["par1_0","par1_1","par1_2"],["par2_0","par2_1","par2_2"]];
我想在以下字符串数组中转换此数组:
var result = [["par0_0,par1_0,par2_0"],["par0_1,par1_1,par2_1"],["par0_2,par1_2,par2_2"]];
最有效的方式是什么?
答案 0 :(得分:2)
您可以toString()
使用array
将数组值转换为字符串并连接它们。
var myArr = [
['par0_0', 'par0_1', 'par0_2'],
['par1_0', 'par1_1', 'par1_2'],
['par2_0', 'par2_1', 'par2_2']
];
var myArrLen = myArr.length,
myOutput = []; // The output array
for (var i = 0; i < myArrLen; i++) {
var arrEl = []; // Initialize the array for inserting sub-array
for (var j = 0; j < myArr[i].length; j++) {
arrEl.push(myArr[j][i]); // Add items from same column into sub-array
}
myOutput[i] = [arrEl.toString()]; // Assign the string to output array
}
document.write(myOutput);
console.log(myOutput);
答案 1 :(得分:1)
您也可以使用reduce()
function两次
[par0_0, par0_1, par0_2].reduce(function(previousValue, currentValue, index, array) {
var result = "";
if (index != 0)
{
result = ",";
}
return result + previousValue + currentValue;
});
答案 2 :(得分:1)
您可以使用join()
。这是一个例子:
var arr = [["par0_0","par0_1","par0_2"],
["par1_0","par1_1","par1_2"],
["par2_0","par2_1","par2_2"]]
for(var i = 0 ; i < arr.length; i++) {
arr[i] = [arr[i].join()] ;
}
如果您不想使用逗号, join()
会接受可选的分隔符参数。默认分隔符为逗号。
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join