在第四章的Eloquent Javascript中获得一个意外的NaN,但这个错误对我来说并不明显。有人会介意看看并指出我的错误吗?typeof var后的意外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
在func
总和for
环后确实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
任何帮助表示赞赏。
'typeof(NaN)'是“数字”。检查'numRng'的值 – scrappedcola