Javascript:如何交换对象数组的元素(通过引用而不是索引)? [英] Javascript: How can I swap elements of an array of objects (by reference, not index)?

查看:117
本文介绍了Javascript:如何交换对象数组的元素(通过引用而不是索引)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组a=[ {v:0}, {v:1}, {v:2}, {v:3} ] ;

我没有索引进入数组,但是我有引用我要交换的2个值

I do not have the index into the array, but I do have references to the 2 values I want to swap

s1=a[2] ; s2 = a[3] ;

如何使用这些引用交换实际数组的元素?

How do I use these references to swap the elements of the actual array?

[s1,s2] = [s2,s1] ; // only swaps s1 and s2, NOT elements of the array

// a is unchanged

推荐答案

如果有引用,则可以通过Array.indexOf()安全地检索索引:

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.

赞:

let a = [{ v: 0 }, { v: 1 }, { v: 2 }, { v: 3 }];

const s1 = a[2];
const s2 = a[3];
console.log(a.indexOf(s1))

这篇关于Javascript:如何交换对象数组的元素(通过引用而不是索引)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆