简体   繁体   English

在javascript中动态添加变量

[英]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. 但是, this不赶我的变量名。 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. 在控制台中,我得到this.itemArray .splice is not a function我也这样尝试过this.itemArray .splice is not a function ,我创建了itemArray变量,以便可以对其进行分配。 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. 并且,如果selectedColors是您的数组,请不要使用引号。

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. 你不能.splice因为字符串.splice 只存在于阵列。 You need to pass in an array to removeItem() . 您需要将array传递给removeItem()

I also noticed that you need to remove the this keyword in front of itemArray . 我还注意到,您需要删除itemArray前面的this关键字。 this is not the this you are trying to reference. this是不是this你尝试引用。

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. 在JavaScript中, this引用您从中调用函数的上下文。 What you could do is 你能做的是

removeItem.call(yourArray, index);

Then this would reference your array in your function. 然后, this将在函数中引用您的数组。 But in your case you can just remove the this because the passed in arguments are available without it. 但是在您的情况下,您只能删除this因为没有它就可以使用传入的参数。

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. selectedColors是一个字符串,而不是一个数组, string.splice()将始终返回错误。 Make sure you pass the array to selectedColors . 确保将数组传递给selectedColors

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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