gpt4 book ai didi

javascript - typeof var 显示预期的数字类型后出现意外的 NaN 输出

转载 作者:数据小太阳 更新时间:2023-10-29 05:57:00 25 4
gpt4 key购买 nike

在 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 输出,在 func 中的 for 循环之后显示 typeof total sum 确实是 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

感谢任何帮助。

最佳答案

问题就在这里

for ( i = 0; i <= numRng.length; i++ )
^

numRng[numRng.length] => 未定义
我更正了下面的代码

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

关于javascript - typeof var 显示预期的数字类型后出现意外的 NaN 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com