【问题标题】:JS - Check for existence of a value in array and if true assign a valueJS - 检查数组中是否存在值,如果为真则赋值
【发布时间】:2018-04-21 08:36:02
【问题描述】:

我正在检查数组中是否存在某个值,如果存在,我想分配一个特定于 myArray 中的值的值。下面的代码有效,但有很多重复。有没有更好的做事方式?

const myArray = ['a', 'b', 'c', 'd'];
const aExists = myArray.indexOf('a') > -1;
const bExists = myArray.indexOf('b') > -1;
const cExists = myArray.indexOf('c') > -1;

return [
    (aExists ? 'value-for-a' : undefined),
    (bExists ? 'or-something-for-b' : undefined),
    (cExists ? 'different-value-for-c' : undefined)
].filter(x => x !== undefined).toString();

【问题讨论】:

    标签: javascript arrays filter indexof


    【解决方案1】:

    创建键/值的字典 (dict)。使用Object.keys(),并使用Array.reduce() 迭代密钥。使用Array.includes() 查找myArray 中的键是否存在,并将dict 中的匹配键添加到结果中:

    const dict = {
      'a': 'value-for-a',
      'b': 'or-something-for-b',
      'c': 'different-value-for-c'
    };
    const myArray = ['a', 'b', 'c', 'd'];
    
    const result = Object.keys(dict)
      .reduce((r, k) => {
        if(myArray.includes(k)) r.push(dict[k]);
      
        return r;
      }, []);
      
    console.log(result);

    【讨论】:

      【解决方案2】:

      您只需为所有预先指定的值创建一个映射器,并通过检查映射器中其键的存在来过滤myArray。然后使用map 创建一个包含预期值的新数组。

      let myArray = ['a', 'b', 'c', 'd'];
      let values = {
        a: 'value-for-a',
        b: 'or-something-for-b',
        c: 'different-value-for-c'
      };
      let results = myArray.filter(v => values[v]).map(v => values[v]);
      console.log(results);

      如果您想要更快的解决方案,那么您可以改用它。

      let myArray = ['a', 'b', 'c', 'd'];
      let values = {
        a: 'value-for-a',
        b: 'or-something-for-b',
        c: 'different-value-for-c'
      };
      let results =[];
      for(let v of myArray) {
        if(!values[v]) continue;
        results.push(values[v]);
      }
      console.log(results);

      【讨论】:

        【解决方案3】:

        显而易见的就是使用ifs的一系列

        const myArray = ['a', 'b', 'c', 'd'];
        if (myArray.indexOf('a') > -1) {
            return 'value-for-a';
        }
        if (myArray.indexOf('b') > -1) {
            return 'or-something-for-b';
        }
        if (myArray.indexOf('c') > -1) {
            return 'different-value-for-c';
        }
        return '';
        

        或者一个值的映射和一个循环

        const myArray = ['a', 'b', 'c', 'd'];
        const values = {a: 'value-for-a', b: 'or-something-for-b', c: 'different-value-for-c'};
        for (const key of Object.keys(values)) {
            if (myArray.indexOf(key)) {
                return values[key];
            }
        }
        return '';
        

        【讨论】:

          【解决方案4】:

          您可以创建一个对象数据结构,以检查数组中的索引并获取新值。当该键的索引存在于数组 myArray 中时,您可以简单地将与该索引对应的值推送到结果数组中:

          const mapObj = {
            'a': 'value-for-a',
            'b': 'or-something-for-b',
            'c': 'different-value-for-c'
          };
          const myArray = ['a', 'b', 'c', 'd'];
          
          var res = [];
          Object.keys(mapObj).forEach((key)=>{
            if(myArray.indexOf(key) !== -1){
              res.push(mapObj[key]);
            }
          });
          
          console.log(res);

          另外,我建议使用indexOf() 而不是includes() 作为includes() IE浏览器会报错。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Browser_compatibility

          【讨论】:

            【解决方案5】:

            为所需的新数组的可能值创建一个对象,然后遍历其条目以将其转换为所需的格式:

            const myArray = ['a', 'b', 'c', 'd'];
            const newArrValues = {
              a: 'value-for-a',
              b: 'or-something-for-b',
              c: 'different-value-for-c',
            };
            const result = Object.entries(newArrValues)
              .filter(([key]) => myArray.includes(key))
              .map(([_, value]) => value)
              .toString();
            console.log(result);

            【讨论】:

              【解决方案6】:

              您可以使用in operator 并使用所需字符串的对象过滤数组的项目,然后映射值。

              var array = ['a', 'b', 'd'];
                  data = {
                      a: 'value-for-a',
                      b: 'or-something-for-b',
                      c: 'different-value-for-c',
                      e: 'foo'
                   },
                   result = array
                       .filter(k => k in data)
                       .map(k => data[k]);
                   
              console.log(result);

              【讨论】:

                猜你喜欢
                • 2017-09-17
                • 2022-12-04
                • 2021-01-16
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多