how to push an element at index 0 of an array
本问题已经有最佳答案,请猛点这里访问。
我遇到这样的情况,
我有两个
和
埃多克斯1〔2〕
我的问题是:我怎么能从
埃多克斯1〔6〕
据此,我可以确定
我的
如果我能得到
我的示例数据:
1 2 3 4 | array1 = ["fruit","vegetables"]; array2 = [["apple","banana"],["tomato"]]; //expected output :[["fruit","apple","banana"],["vegetables","tomato"]]; |
采用
1 2 3 4 5 6 7 8 9 10 11 12 13 | var array1 = ["fruit","vegetables"], array2 = [ ["apple","banana"], ["tomato"] ]; var array3 = array2.map(function(v, i) { // iterate over the array to generate the new array var arr = v.slice(); // copy the array arr.unshift(array1[i]) // insert element at beginning return arr; /// return generated array }); console.log(array3) |
更新:如果不想创建新的数组,那么可以避免复制部件。
1 2 3 4 5 6 7 8 9 10 11 | var array1 = ["fruit","vegetables"], array2 = [ ["apple","banana"], ["tomato"] ]; array2.forEach(function(v, i) { // iterate over the array v.unshift(array1[i]) // insert element at beginning }); console.log(array2) |
号
带ES6箭头功能:
1 2 3 4 5 6 7 8 9 | var array1 = ["fruit","vegetables"], array2 = [ ["apple","banana"], ["tomato"] ]; array2.forEach((v, i) => v.unshift(array1[i])); console.log(array2) |
试试这个
1 2 3 4 5 | array1 = ["fruit","vegetables"]; array2 = [["apple","banana"],["tomato"]]; array2.map((a,i) => a.unshift(array1[i])) console.log(array2) |
。