.concat()方法不起作用

时间:2017-07-22 14:18:17

标签: javascript

我正在运行以下script



var result = [];
var data1 = ['a', 'b', 'c'];
var data2 = ['d', 'e', 'f'];
for (var i = 0; i < data1.length; i++) {
  var tepmArray = [];
  var tempArray1 = [];
  tepmArray.push(data1[i]);
  for (var j = 0; j < data2.length; j++) {
    tempArray1 = [];
    tempArray1.push(data2[j]);
    tepmArray.concat(tempArray1);
  }
  result.push(tepmArray);
}
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

它提供了以下输出

[
    [
        "a"
    ],
    [
        "b"
    ],
    [
        "c"
    ]
]  

我期待跟进

[
    [
        "a", "d", "e", "f"
    ],
    [
        "b", "d", "e", "f"
    ],
    [
        "c", "d", "e", "f"
    ]
]  

我的代码出了什么问题。

4 个答案:

答案 0 :(得分:0)

var result = [];
var data1 = ['a', 'b', 'c'];
var data2 = ['d', 'e', 'f'];
for(var i = 0; i < data1.length; i++) {
var tepmArray = [];
//var tempArray1 = [];
tepmArray.push(data1[i]);
for (var j = 0; j < data2.length; j++) {
tepmArray.push(data2[j]);
}
result.push(tepmArray);
tepmArray=[];
}
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 1 :(得分:0)

你好你应该为你的data1数组的每个循环推送你的结果数组中的所有tempArray(这里是3次):

var result = [];
var data1 = ['a', 'b', 'c'];
var data2 = ['d', 'e', 'f'];
var data1Length = data1.length;

for (var i = 0; i < data1Length; i++) {
    var tempArray = [];
    tempArray.push(data1[i]);
    for(var j = 0; j < data1Length; j++) {
       tempArray.push(data2[j]); 
    }
    result.push(tempArray);
}
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

https://jsfiddle.net/80zp1hu4/

答案 2 :(得分:0)

var result = [];
var data1 = ['a', 'b', 'c'];
var data2 = ['d', 'e', 'f'];
for (var i = 0; i < data1.length; i++) {
    var tepmArray = [];
    var tempArray1 = [];
    tepmArray.push(data1[i]);
    for (var j = 0; j < data2.length; j++) {
        tempArray1.push(data2[j]);
    }
    tepmArray = tepmArray.concat(tempArray1);
    result.push(tepmArray);
}
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

//You have reinitialized tempArray1 inside inner loop, 
//and concat function returns new array. So you have to reassign it.

答案 3 :(得分:0)

为什么不在每个迭代中映射data1和concat的数据然后将data2的数据映射到新数组?

var data1 = ['a', 'b', 'c'],
    data2 = ['d', 'e', 'f'],
    result = data1.map(function (a) {
        return [a].concat(data2);
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }