为什么函数产生错误的解决方案

时间:2017-02-04 23:32:33

标签: javascript arrays function

   <script>
    function range (start , end ) {
      var list =[]
      for (var count = start ; count <= end ; count++)
        list.push(count);
      return list
    }

    function sum ( nums ) {
      var total = 0;
      for ( var count = 0 ; count <= nums.length ; count++ )
        total = total + nums[count];
      return total;
    }

    console.log(range(1 , 10))
    console.log(sum(range(1 ,10)))
    </script>

当我运行此功能时,sum功能的输出将为NaN。我知道解决方案是从=函数中删除sum但是我不明白这是如何解决问题的。

2 个答案:

答案 0 :(得分:5)

您正在迭代超出nums数组的范围。 因此,在循环的最后一次迭代中,您可以有效地执行total = total + undefined,其结果为NaN。 例如,在JavaScript控制台中,n + undefined会生成NaN,其中n是任意数字。

将循环条件更改为count < nums.length而不是<=

  for ( var count = 0 ; count < nums.length ; count++ )
    total = total + nums[count];

答案 1 :(得分:1)

当你&lt; =表示你包括结束号码时。所有数组都被0索引,这意味着第一个项目位于索引0

对于10个项目的数组,这意味着最后一个索引是9

也可以使用+=

增加现有数字

&#13;
&#13;
function range (start , end ) {
  var list =[]

  //here you want INCLUSIVE because you are starting 
  //at VALUE 1 and ending at VALUE 10
  for (var count = start ; count <= end ; count++)
    list.push(count);
  return list
}

function sum ( nums ) {
  var total = 0;

  //here you want EXCLUSIVE because you are starting
  //at INDEX 0 and ending at INDEX 9
  for ( var count = 0 ; count < nums.length ; count++ )
    total += nums[count];
  return total;
}

console.log(sum(range(1,10)))
&#13;
&#13;
&#13;