<html>
<head>
</head>
<body>
<p id="test"> </p>
<script>

function numbers() {
  var qwe,
  zxc = - Infinity;
  // arguments.length == 4 , right?
  for (qwe = 0; qwe < arguments.length; qwe++) {
    if (arguments[qwe] > zxc) {
      // If arguments[qwe] which is equalto11isgreaterthan - Infinity--TRUE, right ?
      zxc = arguments[qwe]; // why does the output become 25 ?
    }
  }
  return zxc; // is it because of this ?
}
document.getElementById('test').innerHTML = numbers(13, 10, 25, 11);

</script>
</body>
</html>


为什么输出变为25?

最佳答案

Arguments.length等于4,因为您已经发送了4个参数(13、10、25、11)。您的for循环遍历4个参数,然后找到参数[qwe]。让我们分解一下:


第一次通过for循环,qwe = 0且zxc =-Infinity,因此if语句的计算结果为true(参数[0] = 13,并且13>-Infinity)。因为if语句的值为true,所以我们现在评估if语句内部的逻辑,因此zxc现在设置为等于arguments [0],即13。
通过for循环的下一轮,qwe现在为1,zxc仍为13,arguments [qwe] = 10(下一个参数)。现在,arguments [qwe] = 10,不大于zxc(13),因此if语句为false,并且if语句中的逻辑不被评估。
在for循环的下一次迭代中,qwe = 2,zxc仍为13,并且arguments [qwe] = 25(下一次迭代)。现在,arguments [qwe] = 25,它大于zxc(13),因此if语句为true。因为if语句的计算结果为true,所以我们评估if语句内部的逻辑,并且zxc现在设置为相等的arguments [2],即25。
对于for循环的下一次也是最终一次迭代,qwe = 3,arguments [qwe] = 11,zxc =25。由于arguments [qwe] = 11,不大于25,因此if语句的计算结果为false,而if语句的计算结果为false。 if语句中的逻辑未评估。


此时,qwe =参数长度,因此for循环结束。一旦for循环结束,我们将返回zxc,此时为25。

关于javascript - Js函数参数(数字列表中的最大值),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36110314/

10-12 03:37