如果我调用 console.log(range(1,10)) 我会得到一个 NaN 数组。当参数 Third 进入第一个 if 语句时未定义,该语句的计算结果为 True。当 for 循环运行时,count 被添加到第三个,返回 NaN。
为什么循环不停止?相反,它会循环并将 NaN 添加到数组中。
如果我设置 if(typeofthird !== 'undefined')third 被转换为字符串,但是 JavaScript 如何知道在 for 循环中运行时将third转回数字?
function range(start,end,third){
var numberlist = [];
if(third !== 'undefined'){
if (start < end){
for (var count = start; count < end; count++){
numberlist.push(count + third);
}
}
else {
for (var count = start; count > end; count--){
numberlist.push(count + third);
}
}
}
else {
for (var count = start; count < (end + 1); count++){
numberlist.push(count);
}
}
return numberlist;
}
最佳答案
实际上,您缺少 typeof
运算符:
if(typeof third !== 'undefined'){
或者,您可以检查未定义
:
if(third !== undefined){
以下代码将检查third
是否为字符串undefined
:
if(third !== 'undefined'){
关于javascript - Nan 在检查第三个参数解释时返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910524/