Javascript: 如何交换对象数组的元素(通过引用,而不是索引)?
Javascript: How can I swap elements of an array of objects (by reference, not index)?
我有一个对象数组a=[ {v:0}, {v:1}, {v:2}, {v:3} ] ;
我没有 index 到数组中,但我有 references to 我想交换的 2 个值
s1=a[2] ; s2 = a[3] ;
如何使用这些引用来交换实际数组的元素?
[s1,s2] = [s2,s1] ; // only swaps s1 and s2, NOT elements of the array
// a is unchanged
如果您有参考文献,您可以通过 Array.indexOf()
:
安全地检索索引
a.indexOf(myReference) // returns the index of the reference or -1
然后,有了检索到的索引,您就可以照常进行了。
像这样:
let a = [{ v: 0 }, { v: 1 }, { v: 2 }, { v: 3 }];
const s1 = a[2];
const s2 = a[3];
console.log(a.indexOf(s1))
这是一个效用函数:
function swap(list, a, b) {
var copy = list.slice();
copy[list.indexOf(a)] = b;
copy[list.indexOf(b)] = a;
return copy;
}
// usage
var a =[ {v:0}, {v:1}, {v:2}, {v:3} ] ;
var result = swap(a, a[1], a[3]);
console.log(result);
// [ {v:0}, {v:3}, {v:2}, {v:1} ]
请记住,由于您在数组中使用对象,因此您需要对该值的准确引用。例如。这行不通:
var a =[ {v:0}, {v:1}, {v:2}, {v:3} ] ;
var result = swap(a, {v:1}, {v:3});
console.log(result);
// [ {v:0}, {v:1}, {v:2}, {v:3} ]
这是一个替代版本,它检查数组中的所有值:
function swap(list, a, b) {
return list.map(function(item) {
if (item === a) {
return b;
} else if (item === b) {
return a;
}
return item;
});
}
JavaScript中没有"pass by reference"。在大多数情况下,对象充当指针,而不是引用。
不幸的是,这意味着您需要找到对象的索引,然后使用这些索引交换它们:
// swap here, assumes the objects are really in the array
const s2index = a.indexOf(s2);
a[a.indexOf(s1)] = s2;
a[s2index] = s1;
根据您的用例,您应该检查对象是否确实在数组中。
这里有一个衬垫,以防万一:
a.splice(a.indexOf(s2), 1, a.splice(a.indexOf(s1),1,s2)[0]);
我有一个对象数组a=[ {v:0}, {v:1}, {v:2}, {v:3} ] ;
我没有 index 到数组中,但我有 references to 我想交换的 2 个值
s1=a[2] ; s2 = a[3] ;
如何使用这些引用来交换实际数组的元素?
[s1,s2] = [s2,s1] ; // only swaps s1 and s2, NOT elements of the array
// a is unchanged
如果您有参考文献,您可以通过 Array.indexOf()
:
a.indexOf(myReference) // returns the index of the reference or -1
然后,有了检索到的索引,您就可以照常进行了。
像这样:
let a = [{ v: 0 }, { v: 1 }, { v: 2 }, { v: 3 }];
const s1 = a[2];
const s2 = a[3];
console.log(a.indexOf(s1))
这是一个效用函数:
function swap(list, a, b) {
var copy = list.slice();
copy[list.indexOf(a)] = b;
copy[list.indexOf(b)] = a;
return copy;
}
// usage
var a =[ {v:0}, {v:1}, {v:2}, {v:3} ] ;
var result = swap(a, a[1], a[3]);
console.log(result);
// [ {v:0}, {v:3}, {v:2}, {v:1} ]
请记住,由于您在数组中使用对象,因此您需要对该值的准确引用。例如。这行不通:
var a =[ {v:0}, {v:1}, {v:2}, {v:3} ] ;
var result = swap(a, {v:1}, {v:3});
console.log(result);
// [ {v:0}, {v:1}, {v:2}, {v:3} ]
这是一个替代版本,它检查数组中的所有值:
function swap(list, a, b) {
return list.map(function(item) {
if (item === a) {
return b;
} else if (item === b) {
return a;
}
return item;
});
}
JavaScript中没有"pass by reference"。在大多数情况下,对象充当指针,而不是引用。
不幸的是,这意味着您需要找到对象的索引,然后使用这些索引交换它们:
// swap here, assumes the objects are really in the array
const s2index = a.indexOf(s2);
a[a.indexOf(s1)] = s2;
a[s2index] = s1;
根据您的用例,您应该检查对象是否确实在数组中。
这里有一个衬垫,以防万一:
a.splice(a.indexOf(s2), 1, a.splice(a.indexOf(s1),1,s2)[0]);