Reactjs 状态初始化一个值数组



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

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

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

在映射数组之前,您必须先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,并且不需要解构数组。

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

问题是map不迭代空白空间

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

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

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

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

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

该代码在本机 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() 会产生稀数组,不会使用 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);

最新更新