search

Home  >  Q&A  >  body text

javascript - for loop i problem

There is an array outside the for loop and an object inside the for loop. Each for loop makes an attribute value of the object equal to the corresponding i item of the array and then pushes the object into the empty array. Why is the empty array displayed later? It's exactly the same. Even if I wrap the for with a word execution function, it doesn't work either

某草草某草草2745 days ago717

reply all(6)I'll reply

  • 为情所困

    为情所困2017-05-19 10:47:58

    When you say that the last part of the new array is the same, do you mean that the elements in the array are all the same? It should be a scope issue, which should be solved by using closures.

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:47:58

    When you push the object in the loop body into the empty array, do you do it inside the loop body or after it ends? Isn’t the content in the empty array you mentioned this object?

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:47:58

    let obj={a:1};
    let arr = [{a:1},{a:2},{a:3},{a:1,b:1}];
    let arr2 =[];
    for(let o of arr){
        if(o.a == obj.a){
            arr2.push(o);
        }
    }
    console.log(arr2);//arr2=[{a:1},{a:1,b:1}]

    I guess the function described by the poster should be like this. There is no closure problem. Can the author post the code?

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:47:58

    I have also encountered this type of problem before. After pushing the items looped from a collection into an array, I finally found that the items in the array are all the same. The reason is not very clear. The solution is to first push the items looped into item copy, and then push the value obtained by this copy into the array;

    //此处只是随意举个例子
    var a=[1,2,3,4,5,6];
    var b=[];
    for(let o of a)
    {
        b.push(o.clone());
    }

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:47:58

    talk is cheap,show me the code

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:47:58

    did not send the code , is to brush rogue

    reply
    0
  • Cancelreply