我有一个经常使用的函数来查找对象中的参数值...
let paramDesc = objName.find((e) => e.param1.includes(searchVal));
return paramDesc.param2;
我想变成可重用的代码。这是一个工作示例,其中我对对象和参数进行了硬编码,然后粗略地尝试使其可重用:
const noteLocations = [
{ note: ["D3", "C##3"], locations: ["s6f10", "s5f5", "s4f0"]} ,
{ note: ["D#3", "Eb3"], locations: ["s6f11", "s5f6", "s4f1"]} ,
{ note: ["E3", "Fb3"], locations: ["s6f12", "s5f7", "s4f2"]} ,
{ note: ["F3", "E#3"], locations: ["s6f13", "s5f8", "s4f3"]} ,
{ note: ["F#3", "Gb3"], locations: ["s6f14", "s5f9", "s4f4"]} ,
{ note: ["G3", "F##3"], locations: ["s6f15", "s5f10", "s4f5", "s3f0"]} ,
];
function getNoteById(location) {
let foundLocations = noteLocations.find((e) => e.locations.includes(location));
if (typeof foundLocations !== "undefined") {
return foundLocations.note[0];
} else {
return "Ø";
}
}
console.log("Note: " + getNoteById('s4f4'));
function reusableLookup(search4, objName, param1, param2) {
let parameterDesc = objName.find((e) => e.param1.includes(search4));
if (typeof parameterDesc !== "undefined") {
return parameterDesc.param2[0];
} else {
return "Ø";
}
}
console.log("Note: " + reusableLookup('s4f4',noteLocations, locations, note));
console.log("Note: " + reusableLookup('s4f4',noteLocations, noteLocations.locations, noteLocations.note));
显然,我对这个概念不是很清楚,所以这就是我正在努力学习的内容。这里有很多类似的问题,但我没有看到一个以我可以直接联系以提供答案的方式解决这个问题的问题。
您应该使用动态属性访问,例如
e[param]
而不是 e.param
:
function reusableLookup(search4, objName, param1, param2) {
let parameterDesc = objName.find((e) => e[param1].includes(search4));
if (typeof parameterDesc !== "undefined") {
return parameterDesc[param2][0];
} else {
return "Ø";
}
}
用途:
console.log("Note: " + reusableLookup('s4f4',noteLocations, 'locations', 'note'));
输出:
Note: F#3