【问题标题】:Solve no unused Expression Error with out disabling eslint?在不禁用 eslint 的情况下解决没有未使用的表达式错误?
【发布时间】:2021-09-02 13:16:53
【问题描述】:

我正在使用反应。我有一个函数可以连接对象的键并将结果作为字符串返回。我收到一个看起来像这样的错误: 第 64:7 行:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions

我的功能如下所示。

const allConcat = (listOfObj) => {
    let stringConcat = '';
    Object.keys(listOfObj).map((item, i)=>{
      (listOfObj[item] === 1)? stringConcat += item : null
    });
    return stringConcat
  }

这是每个版本的一个,我也收到了一个错误。

  const allConcat = (listOfObj) => {
    let stringConcat = '';
    Object.keys(listOfObj).forEach(item =>{
      (listOfObj[item] === 1)? stringConcat += item : null
    });
    return stringConcat
  }

请告诉我我可以做些什么来摆脱这个错误。除了禁用 linter。

【问题讨论】:

  • 我已将代码更改为用于每个,但仍然出现此错误。
  • `const allConcat = (listOfObj) => { let stringConcat = ''; Object.keys(listOfObj).forEach(item =>{ (listOfObj[item] === 1)? stringConcat += item : null });返回 stringConcat } @James

标签: javascript node.js reactjs react-native eslint


【解决方案1】:

改变这个

const allConcat = (listOfObj) => {
    let stringConcat = '';
    Object.keys(listOfObj).map((item, i)=>{
      (listOfObj[item] === 1)? stringConcat += item : null
    });
    return stringConcat
  }

到这里

const allConcat = (listOfObj) => Object.entries(listOfObj)
    .filter(([key, val]) => val === 1)
    .map(([key]) => key)
    .join('')

【讨论】:

  • 完美!非常感谢!
【解决方案2】:

您可以使用 array.reduce 来实现相同的目的,而不必创建 let 常量或迭代两次:

const allConcat = (listOfObj) => 
 Object.keys(listOfObj).reduce((acc, curr, index, array) => 
  listOfObj[curr] === 1 ? acc.concat(array[index + 1] ? `${curr}, `: curr) : acc,
 '');

【讨论】:

  • 这是完美的。我想在每个键之间添加一个“,”。有没有办法对每个项目都这样做,并且在字符串末尾没有额外的逗号? @jean182
猜你喜欢
  • 2020-12-25
  • 2019-07-13
  • 2019-02-15
  • 1970-01-01
  • 2016-10-12
  • 2021-03-26
  • 2019-05-02
  • 2021-01-08
  • 2017-09-20
相关资源
最近更新 更多