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

JavaScript如何在search箭头函数内声明变量避免onde函数重复调用

解决方案

要实现仅调用一次onde函数,只需要把filter的单行隐式返回箭头函数,改成带花括号的块级写法,先存储onde的返回值再做判断即可:

const search = (what, arr) => arr.filter((el) => {
  const part = onde(what, el); // 仅调用一次onde函数,结果存入变量复用
  return part.tag.includes(part.input);
});

注意修复原代码的隐藏问题

你当前的onde函数存在全局变量污染问题:直接修改了外层定义的全局数组array,每次调用onde都会覆盖同一个对象的值,会导致运行结果不符合预期,需要同步修改onde函数,将变量都声明为局部作用域,每次调用返回独立的新对象:

function onde(what,where) {
  const array1 = []; // 声明为局部变量,避免污染全局
  const tags = what.split(':')[0];
  const tag = tags.split(','); 
  tag.forEach(element => {
    array1.push(where[element]);
  });
  // 每次返回独立的新对象
  return {
    tag: array1.join(' ').toLowerCase(),
    input: what.split(':')[1].toLowerCase()
  };
}

另外filter方法永远返回数组,不会返回空值,原代码中if (serached)判断永远为真,建议改成判断数组长度serached.length。

完整可运行代码

const search = (what, arr) => arr.filter((el) => {
  const part = onde(what, el);
  return part.tag.includes(part.input);
});

function exibe(el, index, array) {
  console.log(index + " = " + el.name + " " + el.value + " " + el.other);
}

function onde(what,where) {
  const array1 = [];
  const tags = what.split(':')[0];
  const tag = tags.split(','); 
  tag.forEach(element => {
    array1.push(where[element]);
  });
  return {
    tag: array1.join(' ').toLowerCase(),
    input: what.split(':')[1].toLowerCase()
  };
}

var array = [
  { name:"string 1", value:"this A", other: "that 10" },
  { name:"string 2 this", value:"those B", other: "that 20" },
  { name:"string 3", value:"this C", other: "that 30" }
];
const serached = search("name,value:this",array);
if (serached.length) {
  serached.forEach(exibe);
} else {
  console.log('No result found');
}

运行后输出:

0 = string 1 this A that 10
1 = string 2 this those B that 20
2 = string 3 this C that 30

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:15:07