簡體   English   中英

在javascript中動態添加變量

[英]Dynamically add variable to this in javascript

我一直試圖創建一個刪除功能,以從不同的數組中刪除項目。 我的函數就是這樣,它接受數組名稱和該數組中項目的索引。

removeItem(itemArray, index){
   this.itemArray.splice(index,1);
}

然后像

removeItem('selectedColors',5);

但是, this不趕我的變量名。 在控制台中,我得到this.itemArray .splice is not a function我也這樣嘗試過this.itemArray .splice is not a function ,我創建了itemArray變量,以便可以對其進行分配。 好吧,效果不佳。

removeItem(itemArray, index){
   this.itemArray = itemArray;
   this.itemArray.splice(index,1);
}

做就是了

removeItem(itemArray, index){
    itemArray.splice(index,1);
}

並且,如果selectedColors是您的數組,請不要使用引號。

removeItem(selectedColors, 5);

在您的示例中,您正在弄亂事情,或者在嘗試執行操作時感到困惑。 你不能.splice因為字符串.splice 只存在於陣列。 您需要將array傳遞給removeItem()

我還注意到,您需要刪除itemArray前面的this關鍵字。 this是不是this你嘗試引用。

請參閱下文,讓我知道是否有幫助。

 function removeItem(itemArray, index) { itemArray.splice(index, index); } var itemArray = ['green', 'blue', 'red']; console.log(itemArray); removeItem(itemArray, 1); console.log(itemArray); 

在JavaScript中, this引用您從中調用函數的上下文。 你能做的是

removeItem.call(yourArray, index);

然后, this將在函數中引用您的數組。 但是在您的情況下,您只能刪除this因為沒有它就可以使用傳入的參數。

我在這里可以看到一個普遍的錯誤...

removeItem('selectedColors',5);

selectedColors是一個字符串,而不是一個數組, string.splice()將始終返回錯誤。 確保將數組傳遞給selectedColors

let selectedColors = ["red", "blue"];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM