美文网首页
new Array() with fill()

new Array() with fill()

作者: 该用户太帅没有设置昵称 | 来源:发表于2020-02-03 16:01 被阅读0次

因为题目需要建立一个一定长度的2维数组,数组中的每一项都是一个新的数组。
然后就想偷一个懒,用new Array() 和 fill() 实现

// foo.ts
 module.exports = (s: string) => {
   const len = s.length,
            arr = new Array(len);
   arr.fill([])
   return arr
}

// boo.ts
import foo from './foo'
const a = foo("new")
console.log(a) // [[],[],[]]

看上去打印的值是不是很完美。结果在我后续的操作就出现了问题,在赋值的时候就是讲填充的数组全部赋值。

// boo.ts
...
a[0][0] = 1
console.log(a) // [[1],[1],[1]]

具体原因是因为所有的2维数组都是一个引用地址,修改的所有的数组都是同一个。想要避免这种问题,需要用循环赋值不同的引用地址的数组。

相关文章

网友评论

      本文标题:new Array() with fill()

      本文链接:https://www.haomeiwen.com/subject/rjihxhtx.html