Javascript将数组元素交换到另一个索引并删除旧索引

Javascript swap array element to another index and removing the old index

本文关键字:索引 删除 另一个 数组元素 交换 Javascript      更新时间:2023-09-26

是否可以将数组元素包含的对象的引用交换到另一个索引,并移除/删除旧索引。

示例:我有一个OBJECTS数组,索引为A、B、C、D。

现在,我想创建一个索引为F的新数组元素,并为其分配索引B所包含对象的引用。之后,我想从数组中删除B,这样只剩下A、C、D、E。

我基本上想做的是复制索引B包含的对象的引用,并将其复制到E.

我试过下面的代码,但它不起作用:

this.cache['A'] = new Orange(1);
this.cache['B'] = new Orange(2);
this.cache['C'] = new Orange(3);
this.cache['D'] = new Orange(4);
// I want to pass the reference B contains
// and assign it to F (like something you can do in C++)
this.cache['E'] = this.cache['B'];  
// First attempt
// length of array is 5 (cache['B'] just has value of undefined)
delete this.cache['B'];
// Second attempt
// the reference to object Orange was deleted in both B and E
this.cache.splice('B', 1);

我不想创建一个新对象并重新分配值,因为有很多对对象的引用和绑定,所以进行深度复制是没有意义的。

我想知道为什么"splice"方法不是解决方案。

看看我的示例代码。我在那里使用剪接,没有任何参考资料丢失。。。

function Oo(s) {
    this._s = s;
}
Oo.prototype.toString = function() {
    return "-" + this._s+"-";
}
var a = [];
a.push(new Oo('x'));
a.push(new Oo('y'));
a.push(new Oo('z'));
a[3] = a[1];
alert(a);  // -x-,-y-,-z-,-y-
a[3]._s = 'XX'; // let's change the newly added item
alert(a); // -x-,-XX-,-z-,-XX- <- 3 and 1 points to the same object!
a.splice(1, 1); // remove one element, starting from index = 1
alert(a); // -x-,-z-,-XX-

要取消设置对象属性,可以使用"delete"运算符。例如:

var f ={
    test1: "fire",
    test2: "water"
}
console.log(f.test2)
//Output water
delete f.test2;
console.log(f.test2)
//Output undefined

为了解决你的整体问题,你可以使用类似的东西。

this.cache['A'] = new Orange(1);
this.cache['B'] = new Orange(2);
this.cache['C'] = new Orange(3);
this.cache['D'] = new Orange(4);
this.cache['E'] = this.cache['B'];
delete this.cache['B'];

您确定对象引用不再使用E吗?

此代码:

var cache = {};
cache['B'] = new Object( {"hello": "world"} );
cache['E'] = cache['B'];
delete cache['B'];

现在,缓存['E']仍然包含分配给缓存['B']的对象。

> cache['E'].hello
"world"
>

以下内容是否足够?

var myArray= ['a','b','c','d'];
myArray[4] = myArray[1];
myArray.splice(1,1)
var stuff = myArray.join("");
document.write(stuff)

结果:acdb

看看这篇文章

我希望您使用的是对象而不是数组。Javascript中没有对象的属性length

作为数组。在这里,即使它被声明为数组,也不会向数组中添加值(如php等)。而是作为属性添加。所以长度总是零。

this.cache = [];
this.cache['A'] = 1;
this.cache['B'] = 2;
this.cache['C'] = 3;
this.cache['D'] = 4;
this.cache['E'] = this.cache['B'];
delete this.cache['B'];
console.log(this.cache['B'], this.cache.length, this.cache.hasOwnProperty('B'));

正如您在上面的示例中看到的,this.cache没有用作数组。所以你可以创建和对象。

this.cache = {};
this.cache['A'] = 1;
this.cache['B'] = 2;
this.cache['C'] = 3;
this.cache['D'] = 4;
this.cache['E'] = this.cache['B'];
delete this.cache['B'];
console.log(this.cache['B'], this.cache.length, this.cache.hasOwnProperty('B'));

在这两种情况下,hasOwnProperty('B')都将返回false。如果对象具有属性B,则hasOwnProperty将返回true。你的第一种方法应该有效。

http://jsfiddle.net/diode/hfLJz/1/