2017-07-22 95 views
-6

我運行以下script.concat()方法不能正常工作

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>');

它提供了以下出來把

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

我指望下面放出來

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

我的代碼有什麼問題。

+2

閱讀'陣列#concat'的文檔。認真。它在第一段。 – Tomalak

+1

'.concat()'返回一個新的數組。 – Pointy

回答

0

爲什麼不只是映射data1和concat的值,然後是的數據在每個迭代中的新數組?

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; }

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>'); 

0

你好,你要推動所有tempArray你的結果陣列內爲您的數據1陣列中每一個環(SO 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/

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.