在Eloquent Javascript第4章的练习中获得意外的NaN,但错误不足以让我接受它。有人会介意看看我的错误吗?
/*
Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.
*/
var numRng = [];
function range( start, end ) {
//var numRng = [];
cntr = ( end - start );
for ( i = 0; i <= cntr; i++ ) {
numRng.push( start );
start++;
} // end FOR
//return numRng;
} // end FUNC range
range( 1, 10 );
/*for ( i = 0; i < numRng.length; i++ ) {
console.log( 'Array element ' + numRng.indexOf( 1 + i ) + ' contains range value: ' + numRng[i] );
}*/
/*
Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.
*/
var total = 0;
function sum( numRng ) {
//var total = 0;
for ( i = 0; i <= numRng.length; i++ ) {
//console.log( total );
total += numRng[i];
//console.log( total );
} // end FOR
console.log( typeof total );
console.log( total );
} // end FUNC range
sum( numRng );
console.log( 'Total sum of all element values held by array numRng is: ' + total );
这是Firebug输出,在typeof total
总和中的for
循环确实func
之后显示number
,然后输出为NaN
。
var numRng = []; // seem to require global var ...nt values held by array numRng is: ' + total );
number
NaN
Total sum of all element values held by array numRng is: NaN
任何帮助表示感谢。
答案 0 :(得分:6)
问题出在这里
for ( i = 0; i <= numRng.length; i++ )
^
numRng[numRng.length]
=&gt;未定义
我更正了下面的代码
var numRng = [];
function range( start, end ) {
//var numRng = [];
cntr = ( end - start );
for ( i = 0; i <= cntr; i++ ) {
numRng.push( start );
start++;
}
}
range( 1, 10 );
var total = 0;
function sum( numRng ) {
for ( i = 0; i < numRng.length; i++ ) {
total += numRng[i];
}
console.log( typeof total );
console.log( total );
}
sum( numRng );
console.log( 'Total sum of all element values held by array numRng is: ' + total );
&#13;
答案 1 :(得分:3)
这里唯一的错误是你有
for ( i = 0; i <= numRng.length; i++ )
哪个应该是
for ( i = 0; i < numRng.length; i++ )
数组的长度是最后一个索引+ 1;所以当在循环的最后一次迭代中使用&lt; =时,numRng [i]将是未定义的,并且向undefined添加一个数字会给你NaN。