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