簡體   English   中英

array.push(object)未在javascript循環的末尾推送

[英]array.push(object) not pushed at the end of the loop in javascript

var temparray1 = [[1,3,4],[5,6,7],[8,9,10]];
var final = [];
var obj = {};
for(var temp in temparray1){
    for(var test in temparray1[temp]){
        obj.b = temparray1[temp][0];
        obj.c = temparray1[temp][1];
        obj.d = temparray1[temp][2];
    }
    console.log(obj);
    final.push(obj);
}

電流輸出

[{ b: 8, c: 9, d: 10 }
{ b: 8, c: 9, d: 10 }
{ b: 8, c: 9, d: 10 }]

預期輸出

[{ b: 1, c: 3, d: 4 }
{ b: 5, c: 6, d: 7 }
{ b: 8, c: 9, d: 10 }]

我在node.js -v 8.1.x服務器中運行我的JavaScript

在控制台中for循環的末尾,它將打印所需的輸出,但不打印在數組推中

可能是將obj設置在for循環之外,因此道具被覆蓋,並且將同一對象多次推入數組。 只需將obj聲明移入循環即可。 您可能只需要外部循環。

順便說一句:

let final = temparray1.map(
 ([b,c,d]) => ({b,c,d})
);

這就是你想要的

var temparray1 = [[1,3,4],[5,6,7],[8,9,10]];
var final = [];
for(var temp in temparray1){
   var obj = {};
   obj['b'] = temparray1[temp][0];
   obj['c'] = temparray1[temp][1];
   obj['d'] = temparray1[temp][2];
   final.push(obj);
}
console.log(final);

希望這可以幫助!

 var temparray = [[1, 3, 4], [5, 6, 7], [8, 9, 10]]; const final = temparray.map(a => ({ b: a[0], c: a[1], d: a[2] })); console.log(final); 

您可以使用Array#map並返回具有所需屬性的對象。

 var array = [[1, 3, 4], [5, 6, 7], [8, 9, 10]], result = array.map(function (a) { return { b: a[0], c: a[1], d: a[2] }; }); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

使用ES6,您可以使用Object.assignspread語法...映射內部數組和鍵數組。

 var array = [[1, 3, 4], [5, 6, 7], [8, 9, 10]], keys = ['b', 'c', 'd'], result = array.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] })))); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM