JavaScript 中数组的fill 踩坑

810 阅读1分钟

JavaScript 中数组的fill方法 爬坑

Array.fill() 函数用于使用给定的静态值填充数组。该值可用于填充整个数组,也可用于填充数组的一部分。

注意: 给定的时静态值 使用object填充数组时, 数组中的对象都将是同一个, 这样你在更改对象中的数据时会牵一发而动全身的效果 一定要用的话, 重新赋值吧

tips:

// 导入表格
importExcel = (e) => {
  if (e.file.response) {
    const workBook = e.file.response
    const list = [];
    const data = workBook[0] ? workBook[0].data : [];
    // 获取最大长度
    let maxLength = 0
    data.forEach(row => {
      if(maxLength < row.length) {
        maxLength = row.length
      }
    })
    data.forEach(row => {
      const rowValues = Array(maxLength).fill({})
      rowValues.forEach((ritem, index) => {
        rowValues[index] = {
          value: row[index] ? row[index] : ''
        };
      })
      list.push(rowValues);
    })
    this.setState({ sheetData: list })
  }
}