LoginSignup
1
0

More than 5 years have passed since last update.

new Array()の罠

Last updated at Posted at 2018-09-15

既出かもしれませんが、こんなくだらないことで累計数時間ハマって悔しいので

つまずき

普段どうやって配列初期化してますか?
私は、

const array = new Array(3).fill(null)

とやることが多いのですが、2次元配列を作ったときについ

const matrix = new Array(3).fill(new Array(3).fill(null))

とやってしまい、ドツボにはまりました。

原因

なにが悪いかというと、

matrix[0] === matrix[1] // true

です。鳥肌モノですね。
ご存知の通り配列は

[] === [] // false
new Array() === new Array() // false

なのですが、Arrayをfillするとtrueになってしまうようです?

当然、配列は参照型なので、

console.log(matrix[0][0]) // null
console.log(matrix[1][0]) // null

matrix[0][0] = "hoge"
console.log(matrix[0][0]) // "hoge"
console.log(matrix[1][0]) // "hoge"

しんどい。

対策

楽しようとせず、丁寧にfor文を回しましょう

const matrix = new Array(3).fill(null)
for(let i in matrix) {
    matrix[i] = new Array(3).fill(null)
}
console.log(matrix[0] === matrix[1]) // false

または、

let matrix = new Array(3).fill(null)
matrix = matrix.map(v => new Array(3).fill(null))
console.log(matrix[0] === matrix[1]) // false

ふぅ…


ちなみに関係ないですが、

const matrix = new Array(3).fill(null)
for(let i in matrix) {
    console.log(typeof i) // "string"
}

世知辛いのじゃ

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0