计算数组平均值
使用 reduce
方法
1 2 3 4
| const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); const average = sum / numbers.length; console.log(average);
|
使用 forEach
方法
1 2 3 4 5
| const numbers = [1, 2, 3, 4, 5]; let sum = 0; numbers.forEach(number => sum += number); const average = sum / numbers.length; console.log(average);
|
使用 map
和 reduce
方法
1 2 3 4 5 6 7 8
| const numbers = [1, 2, 3, 4, 5]; const sumAndCount = numbers.reduce((acc, val) => { acc.sum += val; acc.count++; return acc; }, { sum: 0, count: 0 }); const average = sumAndCount.sum / sumAndCount.count; console.log(average);
|
获取数组最大值
使用 Math.max
和 apply
1 2 3
| const numbers = [1, 2, 3, 4, 5]; const max = Math.max.apply(null, numbers); console.log(max);
|
使用 Math.max
和扩展运算符
1 2 3
| const numbers = [1, 2, 3, 4, 5]; const max = Math.max(...numbers); console.log(max);
|
使用 reduce
方法
1 2 3
| const numbers = [1, 2, 3, 4, 5]; const max = numbers.reduce((a, b) => Math.max(a, b)); console.log(max);
|
使用 sort
方法
1 2 3 4
| const numbers = [1, 2, 3, 4, 5]; numbers.sort((a, b) => b - a); const max = numbers[0]; console.log(max);
|
使用 for
循环
1 2 3 4 5 6 7 8
| const numbers = [1, 2, 3, 4, 5]; let max = numbers[0]; for(let i = 1; i < numbers.length; i++) { if(numbers[i] > max) { max = numbers[i]; } } console.log(max);
|
计算次方
使用 Math.pow
1 2 3 4
| const base = 2; const exponent = 3; const result = Math.pow(base, exponent); console.log(result);
|
使用 **
运算符
1 2 3 4
| const base = 2; const exponent = 3; const result = base ** exponent; console.log(result);
|
获取二维数组内层最小数组的长度
1 2 3 4 5
| const arrayOfArrays = [[1, 2, 3], [1, 2], [1, 2, 3, 4, 5], [1]]; const minLength = arrayOfArrays.reduce((min, arr) => { return Math.min(min, arr.length); }, Infinity); console.log(minLength);
|
或者使用 map
和 Math.min
1 2 3 4
| const arrayOfArrays = [[1, 2, 3], [1, 2], [1, 2, 3, 4, 5], [1]]; const lengths = arrayOfArrays.map(arr => arr.length); const minLength = Math.min(...lengths); console.log(minLength);
|
以上内容涵盖了在 JavaScript 中对数组进行操作和计算的一些基本知识点。