简体   繁体   English

将es5重构为es6以避免声明临时变量

[英]refactor es5 to es6 to avoid declaring temporary variable

I have a codebase where tempVar are everywhere, just like below example 我有一个代码库,其中到处都是tempVar,就像下面的示例

const tempQuestions = this.state.questions
    const result = tempQuestions.filter(function(value, index1) {
      return index !== index1
    })
    this.setState({
      questions: result
    })

How to avoid such case? 如何避免这种情况?

Edit: 编辑:

Since you know which index value you want to remove. 由于您知道要删除的索引值。 As @undefined mentioned you can use Array.prototype.splice() method to remove the value rather than iterating the entire array 如@undefined所述,您可以使用Array.prototype.splice()方法删除值,而不是遍历整个数组

Check below solution which will remove one index value 检查以下解决方案,该解决方案将删除一个索引值

const { questions } = this.state;
const result = questions.slice();
result.splice(index, 1);
this.setState({
  questions: result
})

This looks pretty straightforward: 这看起来非常简单:

this.setState({
  questions: this.state.questions.filter((q, i) => index !== i)
})

Using splice will require cloning the array first, otherwise setState won't notify a state change. 使用splice将需要首先克隆数组,否则setState不会通知状态更改。 So an iteration is required either way, for that filter makes more sense than splice . 因此,无论哪种方式都需要进行迭代,因为该filtersplice更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM