【问题标题】:JavaScript syntax declare object inside functionJavaScript 语法在函数内声明对象
【发布时间】:2021-12-04 14:44:04
【问题描述】:

我写了一个代码:

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

但它调用了函数onde(),两次。

但这不是必需的。

如何设置part = onde(what,el);

在const search 内?

所以它只能被调用一次,如part.tag 和part.input

   const search = (what, arr) => arr.filter((el) => 
(onde(what,el).tag).includes((onde(what,el).input)));
    
    function exibe(el, index, array) {console.log(index+" = " + el.name +" " + el.value+" " + el.other);}
    function onde(what,where) { array1=[]; tags =what.split(':')[0]; tag =tags.split(','); 
        tag.forEach(element => {  array1.push(where[element]);});
          array['tag']=array1.join(' ').toLowerCase();
          array['input']=what.split(':')[1].toLowerCase();
          return array;
        }
       
        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) {
          serached.forEach(exibe);
        } else {
            console.log('No result found');
        }

【问题讨论】:

    标签: javascript function syntax


    【解决方案1】:

    先保存在变量中。

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

    或

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

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多