[英]Javascript find the nth element of an array
我看了幾個小時的代碼,無法理解它的工作原理以及給出的答案為1的信息。
如果有人可以用易於理解的術語向我解釋這一點(我是Java語言的新手),我將不勝感激。 代碼如下。 謝謝:
var array = [1, 3, 2, 9];
var one = -Infinity;
var two = -Infinity;
var three = -Infinity;
for (i = 0; i < array.length; i++) {
if (array[i] > one) {
three = two;
two = one;
one = array[i];
}
}
console.log(three);
只需考慮循環中的值,您就會知道為什么“三”的最后一個值是1。這些是每次迭代結束時的值:
|---------------------|------------------|---------------------|------------------|
| i=0 | i=1 | i=2 | i=3 |
| three=-inf | three=-inf | three=-inf | three=1 |
| two=-inf | two=1 | two=1 | two=3 |
| one=1 | one=3 | one=3 | one=9 |
|---------------------|------------------|---------------------|------------------|
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.