[removed] How can I swap elements of an array of objects (by reference, not index)?

前端 未结 4 1127
挽巷
挽巷 2021-01-22 11:55

I have an array of objects a=[ {v:0}, {v:1}, {v:2}, {v:3} ] ;

I do not have the index into the array, but I do have references to

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-22 12:03

    There is no "pass by reference" in JavaScript. In most cases, the objects act as pointers, not references anyway.

    That unfortunately means you will need to find the indexes of the objects and then swap them using those indexes:

    // swap here, assumes the objects are really in the array
    const s2index = a.indexOf(s2);
    a[a.indexOf(s1)] = s2;
    a[s2index] = s1;
    

    Depending on your use case, you should check if the objects indeed are in the array.

提交回复
热议问题