javascript - Can someone explain how this finds the max number?
问题描述
var myArray = [1, 12, 3, 5, 6];
var maxValue = null;
for (var i = 0; i < myArray.length; i++) {
if (maxValue === null || maxValue < myArray[i]) {
maxValue = myArray[i];
}
}
// shows 12
I see that it loops through myArray
and checks if maxValue
is equal to null (which it is?) OR if maxValue
is less than current array element (which it also is?) and then assigns maxValue
to the current array element in for loop. How does this find the largest number? Seems so simple but I don't see how it's finding largest integer ...
解决方案
将初始值替换为 0 并删除空测试使其更易于阅读。添加一个 console.log 可以让你跟踪循环的执行。
var myArray = [1, 12, 3, 5, 6];
var maxValue = 0;
for (var i = 0; i < myArray.length; i++) {
console.log( i, myArray[i], maxValue );
if (maxValue < myArray[i]) {
maxValue = myArray[i];
}
}
// shows 12
推荐阅读
- javascript - PWA 是否有通过 HTTP 访问 LAN 设备的解决方法?
- css - 如何从 App 覆盖其他组件的 css
- python - 无法在 python 3.10 上安装 numpy
- c++ - C ++许多读者单写互斥体饥饿
- css - 使用 CSS 在光线附近创建正方形的边缘
- php - 如何在两个 PHP 文件之间使用 session 和 cookie 发送两个参数
- css - `bookdown` 中的交叉引用代码块,类似于图形、表格和方程式
- javascript - jquery .each 函数使用 2 个选择器并将选择器中的值作为键值对添加到数组中
- powerbi - 无法使用 AdventureWorksDW2019 在 Power BI Visuals 中获取按列数据分组的总计
- python - 我无法使用 Selenium 保存 PDF