简体   繁体   English

用拼接交换元素位置后,Javascript数组元素indexOf为-1

[英]Javascript array element indexOf is -1 after swap of element positions with splice

Our array has two elements of type object like this: 我们的数组有两个类型为object的元素,如下所示:

array = [{Member1: "Value1"},{Member2: "Value2"}];

When I get the index of second object like this: 当我像这样获得第二个对象的索引时:

var index = array.indexOf(obj);

I get 1 as the result, which is fine. 结果是1,这很好。 But when I swap the two elements like this to shift this object from right to left and the other 0 index object from left to right: 但是,当我像这样交换两个元素时,将这个对象从右向左移动,另一个0索引对象从左向右移动:

var new_index = index - 1;
array.splice(index, 0, array.splice(new_index, 1)[0]);

and try to get the index of the same object (which I know is present in the array and only its index is 0 now) I get -1 (not found) as the result. 并尝试获取同一对象的索引(我知道该对象存在于数组中,现在仅其索引为0),结果为-1(未找到)。 Whats the problem here? 这里有什么问题?

As you want to swap, rather than splicing it may be better to use a temporary variable. 因为要交换,而不是进行拼接,所以最好使用临时变量。

var array = [{Member1: "Value1"},{Member2: "Value2"}],
    obj = array[1];

function swap(arr, i, j) {
    var t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
    return arr;
}

console.log('before swap', array.indexOf(obj)); // 1

swap(array, 0, 1);
console.log('after swap', array.indexOf(obj)); // 0

EDIT Just tried your code though and I get the expected result of 0 , maybe you've done something to the reference obj is pointing at between the two 编辑虽然尝试了您的代码,但我得到了预期的结果0 ,也许您对引用obj指向了两者之间做了一些操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM