0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

javascriptで配列の中身に数値を入れたいときNaNになってしまう場合

Posted at

配列にキーを指定して数値を入れたいとき初期化しないとNaNになる。
変数を0で初期化しないとNaNになるときがあって、それはすぐわかったが、今回の配列の中だとできなくてハマった。
ぐぐってもわからず、時間がかかってしまった。
どういう場面で、使うか不明だけど、既存のシステムがあって、一部カスタマイズしたいときなど使うことがあるかもしれない

let arrayA = [0, 1, 2, 3, 4]
let arrayB = []
for ( value in arrayA ) {	
	arrayB[0] += Number(value)
}
// NaN

一度キーを指定して0で初期化しておく。

let arrayA = [0, 1, 2, 3, 4]
let arrayB = []
for ( value in arrayA ) {	
	if (! arrayB[0]) {
	    arrayB[0] = 0
	}

	arrayB[0] += Number(value)
}
// 10
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?