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

时间:2012-01-27 17:47:43

标签: javascript arrays reference indexing swap

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

实施例: 我有一组带有索引A,B,C,D的OBJECTS。

现在我想用索引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);

我不想创建新对象并重新分配值,因为对象有很多引用和绑定,因此执行深层复制将毫无意义。

5 个答案:

答案 0 :(得分:0)

要取消设置对象属性,可以使用“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'];

答案 1 :(得分:0)

你确定对象参考不再是E?

此代码:

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

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

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

答案 2 :(得分:0)

以下是否足够?

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

结果:acdb

查看this post

答案 3 :(得分:0)

我希望你使用的是对象而不是数组。 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/

答案 4 :(得分:0)

我想知道为什么“拼接”方法不是解决方案。

查看我的示例代码。我在那里使用拼接,没有任何参考丢失......

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-