欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > JavaScript 数组操作和数学计算

JavaScript 数组操作和数学计算

2025/3/12 22:26:57 来源:https://blog.csdn.net/weixin_45596561/article/details/139771773  浏览:    关键词:JavaScript 数组操作和数学计算

计算数组平均值

使用 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

使用 mapreduce 方法

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.maxapply

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

或者使用 mapMath.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 中对数组进行操作和计算的一些基本知识点。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词