2012-08-07 58 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] 
}