【问题标题】:Reactjs state initialize an array of valuesReactjs 状态初始化一个值数组
【发布时间】:2019-06-22 14:59:38
【问题描述】:

我正在尝试初始化一个布尔值数组,其中数组中的特定位置有不同的值。

如果我这样初始化状态,空就是数组。

state = {
    activeItems: [...new Array(5)].map((item, idx) =>
      idx === 1 ? true : false
    )
}

【问题讨论】:

  • 该问题未包含所有必要的详细信息。见stackoverflow.com/help/mcve... 的工作方式特定于未显示的设置。在禁用下层迭代的 TypeScript 中,它可能无法按预期工作。

标签: javascript arrays reactjs ecmascript-6


【解决方案1】:

你必须先fill你的数组,然后再映射它:

state = {
    activeItems: new Array(5).fill().map((item, idx) => idx === 1)
}

const result = new Array(5).fill().map((item, idx) => idx === 1)
console.log(result)

还可以将idx === 1 ? true : false 简化为idx === 1,并且不需要解构数组。

【讨论】:

    【解决方案2】:

    Array from 为您提供<empty slots> 的数组

    问题是因为map不迭代over empty spaces

    let arr = new Array(5)
    
    let modified = arr.map((e,i)=> console.log(i)) // prints nothing
    console.log('modifed prints nothing')

    使用填充填充空状态

    let arr = new Array(5)
    
    let modified = arr.fill(0).map((e,i)=> console.log(i))  //prints index

    【讨论】:

      【解决方案3】:

      我不确定您为什么提到您的代码返回空数组。因为,它确实返回了预期的输出。

      您可以改用Array.from 来避免您当前遇到的任何不一致:

      const state = {
          activeItems: Array.from({length:5}, (_, idx) => idx === 1)
      }
      
      console.log(state)

      Array.from 的第二个参数是map 函数。

      【讨论】:

        【解决方案4】:

        代码在原生 ES6 中开箱即用:

        [...new Array(5)].map((item, idx) =>
          idx === 1 ? true : false
        )
        

        结果

        [假,真,假,假,假]

        数组。

        与它的任何不一致都是由正在使用的转译器及其对... 数组扩展语法的实现引起的。在某些实现中,它可能会导致代码不兼容,尤其是禁用了 downlevelIteration 编译器选项的 TypeScript。例如,它用于 Stackblitz,甚至在 JS 项目中。如果没有下层迭代,它将被转换为:

        new Array(5).slice().map(function (item, idx) {
            return idx === 1 ? true : false;
        });
        

        new Array(5).slice() 导致 sparse 数组不会被 map 迭代。这种情况可以通过使用Array.fromArray.fill 来保护(正如其他答案已经暗示的那样)。两者都将使用undefined 值填充稀疏数组,这些值可以使用map 进行迭代:

        Array.from(new Array(5)).map((item, idx) => idx === 1);
        
        new Array(5).fill().map((item, idx) => idx === 1);
        

        【讨论】:

          猜你喜欢
          • 2019-01-28
          • 1970-01-01
          • 2015-05-10
          • 2017-08-07
          • 2019-01-25
          • 2019-05-08
          • 2016-04-04
          • 1970-01-01
          • 2019-06-17
          相关资源
          最近更新 更多