简体   繁体   English

Javascript找到数组的第n个元素

[英]Javascript find the nth element of an array

I have looked at this code for a few hours and cannot understand how it works and how it gives an answer of 1. 我看了几个小时的代码,无法理解它的工作原理以及给出的答案为1的信息。

If someone could explain this to me in easy to understand terms (I am new to Javascript) I would really appreciate it. 如果有人可以用易于理解的术语向我解释这一点(我是Java语言的新手),我将不胜感激。 The code is below. 代码如下。 Thank you: 谢谢:

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);

Just think about the values in the loop and you will know why the last value of "three" is 1. These are the values at the end of each iteration: 只需考虑循环中的值,您就会知道为什么“三”的最后一个值是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM