简体   繁体   English

使用动态名称引用JavaScript属性

[英]Reference a javascript property with a dynamic name

I'm using Vue.js and I am wondering how I can call a javascript property in a dynamic way. 我正在使用Vue.js,我想知道如何以动态方式调用javascript属性。 Let's say I pass an argument to a function like this: 假设我将参数传递给这样的函数:

filter: function(items) {
    this.countriesToFilter.splice(index, 1);
},

How can I replace the countries in my this.countriesToFilter call in a dynamic way so I end up with essentially: 如何以一种动态方式替换this.countriesToFilter调用中的国家/地区 ,所以我最终得到了:

this.itemsToFilter.splice(index, 1);

Maybe this way? 也许是这样吗?

filter: function(items) {
    var whatToFilter = items + 'ToFilter';
    this[whatToFilter].splice(index, 1);
},

The answer is yes. 答案是肯定的。

var name = "itemsToFilter";
var myArray = eval("this." + name);

// use myArray

You can also add a safety check so you don't call splice on undefined 您还可以添加安全检查,以免在未定义的情况下调用splice

if (typeof myArray != 'undefined') {
    myArray.splice(index, 1)
}

The only way I can imagine this working is if you pass a string to the function, and interpolate that string into the object-notation, using square-brackets: 我可以想象的唯一工作方式是,如果将字符串传递给函数,然后使用方括号将字符串插入对象表示法中:

filter: function(keyName) {
    this[keyName + 'ToFilter']splice(index, 1);
}

If your existing variable, items (from the question), contains a value of relevance within the function then you'd also need to pass that as an argument also: 如果您现有的变量(来自问题)的items在函数中包含相关性值,那么您还需要将其作为参数传递:

filter: function(keyName, items) {
    this[keyName + 'ToFilter']splice(index, 1);
}

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

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