简体   繁体   English

如何在 javascript { node js } 中将数组对象推送到上一个数组

[英]How to push array object to previous array in javascript { node js }

Here is I am getting issue on traversing array.这是我在遍历数组时遇到问题。 but not getting proper result.但没有得到正确的结果。 first for loop is traversing and in it another loop is traversing.第一个 for 循环正在遍历,其中另一个循环正在遍历。

    var f_array = s_array = {};

    for ( var i = 0; i < 10 ; i++) {

        var v_c = '1500';

        for ( var j = 0; j < 20 ; j++) {

            s_array[j] = 'abc';
        }       

        f_array = { 'v_c' : v_c,  'years' : s_array };  
    }

console.log(f_array);     // showing only last array object that is i = 9 , I want it all of them.

Here I am updating my question with required result should be like below array.在这里,我正在更新我的问题,所需结果应如下所示。

{
  "v_c": "1500",
    "years": {
      "0": "asd",
      "1": "asd",
     .
     .
     .
      "9": "asd"
    }
},
{
  "v_c": "1500",
    "years": {
      "0": "asd",
      "1": "asd",
     .
     .
     .
      "9": "asd"
    }
},
{
  "v_c": "1500",
    "years": {
      "0": "asd",
      "1": "asd",
     .
     .
     .
      "9": "asd"
    }
}
.
.
.
.
.
.

Your final code should be like this你的最终代码应该是这样的

var f_array = [];

for ( var i = 0; i < 10 ; i++) {

    var v_c = '1500',
        s_array = [];

    for ( var j = 0; j < 9 ; j++) {
        s_array.push('abc');
    }       

    f_array.push( { 'v_c' : v_c,  'years' : s_array });  
}

It will create a new array( s_array ) for every f_array entry, so you will have no problem.它将为每个f_array条目创建一个新数组( s_array ),因此您不会有任何问题。 f_array should be an array of objects as you showed. f_array应该是你展示的对象数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM