【JavaScript】Math.maxとMath.minとfilterメソッド

  • このエントリーをはてなブックマークに追加

配列の中の最大値と最小値をMath.maxとMath.minで求めようとしたところ、配列の値にundefinedが含まれているとNaNが返ってくることに注意する。
このため、filter(Boolean)あるいはfilter(value => value)を使ってfalsyな値(false とみなされる値)を全て削除した後にMath.maxとMath.minを使うこと。
falsyな値は次の通りである。
null
undefided
空文字
数値の0
NaN

空の配列に対してMath.maxを使うと-Infinityが返ることに注意する。
空の配列に対してMath.minを使うとInfinityが返ることに注意する。





console.log("Math.max(...[]) = " + Math.max(...[]));
console.log("Math.min(...[]) = " + Math.min(...[]));

let test = [];

test[0]=80;
test[2]=4;
test[5]=48;
test[7]=0;

console.log("test = "+test);

console.log("Math.max(...test) = " + Math.max(...test));
console.log("Math.min(...test) = " + Math.min(...test));

console.log("test.filter(Boolean) = " + test.filter(Boolean));
console.log("test.filter(value => value) = " + test.filter(value => value));

console.log("Math.max(...test.filter(Boolean)) =" + Math.max(...test.filter(Boolean)));
console.log("Math.min(...test.filter(Boolean)) = " + Math.min(...test.filter(Boolean)));

/*

Math.max(...[]) = -Infinity
Math.min(...[]) = Infinity
test = 80,,4,,,48,,0
Math.max(...test) = NaN
Math.min(...test) = NaN
test.filter(Boolean) = 80,4,48
test.filter(value => value) = 80,4,48
Math.max(...test.filter(Boolean)) =80
Math.min(...test.filter(Boolean)) = 4

*/

  • このエントリーをはてなブックマークに追加

SNSでもご購読できます。

コメントを残す

*