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

前端 未结 4 1167
挽巷
挽巷 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:01

    If you have the reference you can safely retrieve the index by Array.indexOf():

    a.indexOf(myReference) // returns the index of the reference or -1
    

    Then, with retrieved index, you can proceed as usual.

    Like this:

    let a = [{ v: 0 }, { v: 1 }, { v: 2 }, { v: 3 }];
    
    const s1 = a[2];
    const s2 = a[3];
    console.log(a.indexOf(s1))

提交回复
热议问题