代码之家  ›  专栏  ›  技术社区  ›  Matt

ReactJS状态初始化值数组

  •  1
  • Matt  · 技术社区  · 6 年前

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

    如果我这样初始化状态,则数组为空。

    state = {
        activeItems: [...new Array(5)].map((item, idx) =>
          idx === 1 ? true : false
        )
    }
    
    4 回复  |  直到 6 年前
        1
  •  1
  •   Treycos    6 年前

    你必须先 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
  •  1
  •   Code Maniac    6 年前

    从中的数组为您提供数组 <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')

    使用fill填充空状态

    let arr = new Array(5)
    
    let modified = arr.fill(0).map((e,i)=> console.log(i))  //prints index
        3
  •  1
  •   adiga    6 年前

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

    你可以使用 Array.from 相反,为了避免任何不一致性,您目前有:

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

    的第二个参数 来自… 是一个 map 功能。

        4
  •  1
  •   Estus Flask    6 年前

    在本机ES6中,代码是现成可用的:

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

    它导致

    [假,真,假,假,假]

    数组。

    任何与之不一致的地方都是由使用中的蒸腾器及其实现 ... 数组排列语法。在某些实现中,它可能导致代码不一致,特别是带有 downlevelIteration 编译器选项已禁用。例如,它在stackblitz中使用,甚至在JS项目中也使用。如果不进行下层迭代,则会产生:

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

    new Array(5).slice() 结果在 稀疏的 不与迭代的数组 map . 这种情况可以通过使用 Array.from Array.fill (正如其他答案已经表明的那样)。两者都将填充稀疏数组 undefined 可以迭代的值 地图 :

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