我正在尝试调用动态命名对象的方法。
我有一些对象,每个对象包含一个名为“ getWeight”的方法。我需要调用这些对象的子集的此方法。但是,对象的子集取决于用户输入的信息,这就是为什么我试图动态构造对象名称并在循环内调用它的'getWeight'方法的原因。
我的代码如下:
// Importing objects containing 'getWeight' method
const Apple = require('../classses/Apple');
const Pear = require('../classes/Pear);
const Carrot = require('../classes/Carrot);
const Potato = require('../classes/Potato);
const promises = {};
const user = 'userX'; // This is the inputted info, could also equal 'userY'.
const searchableFoods = {
userX: ['Apple', 'Pear'],
userY: ['Carrot', 'Potato']
};
for (i = 0; i < searchableFoods[user].length; ++i) {
promises[searchableFoods[user][i]] = new Promise(function(resolve, reject) {
// Below line should behave like: Apple.getWeight(arg1, function....
searchableFoods[user][i].getWeight(arg1, function(response) {
resolve(response);
})
})
}
不幸的是,我收到此错误:
[searchableFoods[user][i].getweight] is not a function
我尝试了多种变体,但无法使其正常工作。可以这样做吗?
答案 0 :(得分:1)
可以定义不使用字符串的数组吗?像这样吗?
const searchableFoods = {
userX: [Apple, Pear],
userY: [Carrot, Potato]
};
答案 1 :(得分:1)
要求所有这些对象都放入单个对象中,而不要包含许多独立变量,然后可以使用简单的属性查找来获得适当的require
ed值。另外,forEach
可能会导致代码更具可读性,并且您可以单独传递函数名称(resolve
),而不是为getWeight
回调定义额外的匿名函数:
const foods = {
Apple: require('../classses/Apple'),
Pear: require('../classes/Pear),
Carrot: require('../classes/Carrot),
Potato: require('../classes/Potato)
};
// ...
searchableFoods[user].forEach((foodName) => {
promises[foodName] = new Promise((resolve) => {
foods[foodName].getWeight(arg1, resolve);
});
});
答案 2 :(得分:1)
您正在尝试访问getWeight
作为字符串'Apple'
的属性,而不是要导入的实际对象Apple
的属性。
将子集数组更改为类似的内容
const searchableFoods = {
userX: [Apple, Pear],
userY: [Carrot, Potato]
};
将最终代码设为
const Apple = require('../classses/Apple');
const Pear = require('../classes/Pear);
const Carrot = require('../classes/Carrot);
const Potato = require('../classes/Potato);
const promises = {};
const user = 'userX' // This is the inputted info, could also equal 'userY'.
const searchableFoods = {
userX: [Apple, Pear],
userY: [Carrot, Potato]
};
for (i = 0; i < searchableFoods[user].length; ++i) {
promises[searchableFoods[user][i]] = new Promise(function(resolve, reject) {
// Below line should behave like: Apple.getWeight(arg1, function....
searchableFoods[user][i].getWeight(arg1, function(response) {
resolve(response);
})
})
}