You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将对象参数传入可复用函数

可复用对象查找函数的正确实现

问题分析

你的代码核心问题有两个:

  • 属性名传递错误:调用reusableLookup时,你传入的locations、note是未定义的变量,必须传递字符串形式的属性名(比如'locations'),因为对象的属性名本质是字符串。
  • 动态属性访问错误:使用.访问属性时,只能用固定的属性名(比如e.locations),如果属性名是动态参数,必须用方括号[]语法(比如e[param1]),否则会把param1当作固定属性名去查找,而非你传入的参数值。

修正后的可复用函数

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 reusableLookup(searchVal, arr, searchProp, returnProp, fallback = "Ø") {
  // 校验传入的数组是否有效
  if (!Array.isArray(arr)) return fallback;
  
  const foundItem = arr.find(item => {
    // 确保要搜索的属性是数组,避免includes方法报错
    return Array.isArray(item[searchProp]) && item[searchProp].includes(searchVal);
  });
  
  // 找到目标项则返回对应属性的第一个元素,否则返回默认值
  return foundItem ? foundItem[returnProp][0] : fallback;
}

// 正确调用:传递字符串形式的属性名
console.log("Note: " + reusableLookup('s4f4', noteLocations, 'locations', 'note'));
// 反向查找示例:通过音符找对应位置
console.log("Location: " + reusableLookup('F#3', noteLocations, 'note', 'locations'));

关键改进点

  1. 动态属性访问:用item[searchProp]和foundItem[returnProp]替代.语法,支持任意属性名的动态查找。
  2. 参数校验:增加数组类型检查,以及搜索属性的数组类型检查,避免运行时报错。
  3. 灵活的默认值:将 fallback 设为可选参数,方便根据场景自定义返回内容。
  4. 简洁逻辑:用三元表达式替代typeof判断,代码更简洁易读。

原错误调用的修正

你原来的错误调用:

console.log("Note: " + reusableLookup('s4f4',noteLocations, locations, note));
console.log("Note: " + reusableLookup('s4f4',noteLocations, noteLocations.locations, noteLocations.note));

修正为传递字符串属性名即可:

console.log("Note: " + reusableLookup('s4f4', noteLocations, 'locations', 'note'));

内容的提问来源于stack exchange,提问作者Realto619

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:27:45