2012-08-07 115 views
6

我想从使用切片的数组中删除一个元素,但是我无法让它工作,请看这段代码。从数组中删除元素,使用切片

console.log(this.activeEffects); // Prints my array 
    console.log(this.activeEffects.slice(0,1)); // Remove from index 0, and remove one. 
    console.log(this.activeEffects); // Prints array again, this time my element should be gone 

结果是这样的。

enter image description here

那么,什么是充分利用这一点,在第一个数组是完整的,因为它应该是。然后,它打印什么是数组的切片。最后第三个应该是空的?要么?

+1

有可能使的jsfiddle这个? – 2012-08-07 14:50:31

+0

你确定这是一个数组吗? – 2012-08-07 14:51:52

回答

12

我相信你正在寻找splice。从W3 Schools:

splice()方法向/从数组中添加/删除项目,并返回删除的项目。

查看该页面上的示例;该用例与您想要实现的类似。

编辑:Alternative link to MDN,如Nicosunshine所建议;有关该命令的更多信息。

+13

我知道我听起来很烦人,但不要使用W3学校。 MDN这是一个更好的资源https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice – NicoSantangelo 2012-08-07 14:54:06

+0

谢谢TSL,这解决了我的问题。现在拍我的自我。 – MartinElvar 2012-08-07 14:55:23

+0

@nicosunshine要Meta要求自动阻止w3schools链接! – canon 2012-08-07 15:14:51

5

.slice不发生变异的数组,你可以使用.splice()在指数i数组中删除项目:

this.activeEffects.splice(i, 1) 
+0

但我可能需要删除一个元素我在数组中间 – MartinElvar 2012-08-07 14:52:34

+0

@MartinElvarJensen对,我没有意识到这一点。当你想从头开始移除时,'shift()'是更可取的。 – Esailija 2012-08-07 14:53:33

+0

切片不会像他所说的那样更改原始数组,但它确实会返回已移除的元素。为什么不通过做一个赋值来将原始数组替换为已删除的元素?例如this.activeEffects = this.activeEffects.slice(0,1) – Magrangs 2012-08-07 14:54:30

1

Array.prototype. slice() ...

不会改变原来的数组,但返回一个新的“一级 深”拷贝包含从 原始数组切片元素的副本。原数组的元素被复制到新的 排列如下:

Array.prototype. splice() ...

改变数组的内容,增加了新的元素,同时消除旧元素。

这个例子应该说明不同之处。

// sample array 
 
var list = ["a","b","c","d"]; 
 
// slice returns a new array 
 
console.log("copied items: %o", list.slice(2)); 
 
// but leaves list itself unchanged 
 
console.log("list: %o", list); 
 
// splice modifies the array and returns a list of the removed items 
 
console.log("removed items: %o", list.splice(2)); 
 
// list has changed 
 
console.log("list: %o", list);

-1

在这里看看: http://www.w3schools.com/jsref/jsref_slice_array.asp

你可以看到,切片方法选择对象等把它们变成一个新的数组对象^^所以你不能删除对象像这样,可能你可以尝试这样的事情:

var a = ["a","b","c"]; (pseudo code) 
/* I wan't to remove the "b" object */ 

var result = a.slice(0,1)+a.slice(2,1); /* If you considers that "+" is a concatenation operator, i don't remember if it is true... */ 
3

这就是我所能够来的了:

var newArray = oldArray.slice(indexOfElementToRemove+1).concat(oldArray.slice(0,indexOfElementToRemove)); 
1
function removeItemWithSlice(index) { 
    return [...items.slice(0, index), ...items.slice(index + 1)] 
} 

切片将创建一个新的数组。我们创建两个数组:从开始到索引,从索引+1到结束。然后我们应用spread运算符(...)来获取这些数组的项目,并创建一个包含我们所关心的所有项目的新单个数组。我会贴一个等效的方式,如果你不喜欢的人内胆:

function removeItemWithSlice(index) { 
    const firstArr = items.slice(0, index); 
    const secondArr = items.slice(index + 1); 
    return [...firstArr , ...secondArr] 
}