简体   繁体   中英

Dynamically add variable to this in javascript

I have been trying to create one remove function to remove items from different array. My function is like this, which accepts array name and index of the item in that array.

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

Then use it like

removeItem('selectedColors',5);

But this does not catch my variable name. In console I get this.itemArray .splice is not a function I also tried like this, I created a itemArray variable so I could assign it. Well, did not work as well.

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

Just do

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

And, if selectedColors is your array, don't use quotation marks.

removeItem(selectedColors, 5);

In your example, you are messing things up or it's confusing on what you are trying to do. You cannot .splice a string since .splice only exists on arrays. You need to pass in an array to removeItem() .

I also noticed that you need to remove the this keyword in front of itemArray . this is not the this you are trying to reference.

See below, and let me know if it helps.

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

In JavaScript this references the context from which you call the function. What you could do is

removeItem.call(yourArray, index);

Then this would reference your array in your function. But in your case you can just remove the this because the passed in arguments are available without it.

I can observe a general mistake here...

removeItem('selectedColors',5);

selectedColors is a string and not an array, string.splice() will always return an error. Make sure you pass the array to selectedColors .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM