为什么这个函数返回NaN?传递一个值减少功能我看到不匹配并返回NAN
function add(a, b) {
return a + b;
}
//add(10);
var result = add(10);
console.log(result);
为什么这个函数返回NaN?传递一个值减少功能我看到不匹配并返回NAN
function add(a, b) {
return a + b;
}
//add(10);
var result = add(10);
console.log(result);
b
是不确定的,当你只能传递10
的功能,因此10 + undefined是你回来的东西;所以NaN
,又名不是数字。
function add(a, b) {
return a + b;
}
//add(10);
var result = add(10,0);
//change this
console.log(result);
欢迎来到SO。请阅读此[如何回答](http://stackoverflow.com/help/how-to-answer)以提供高质量的答案。只发布代码不是一个好答案。 – thewaywewere
这里的问题是,b
是undefined
。因此,另外,JavaScript会尝试将undefined
强制转换为数字。该强制的结果总是NaN
:
console.log(+undefined);
console.log(parseInt(undefined));
console.log(Number(undefined));
,当然还有,许多+ NaN
总是给你NaN
:
console.log(1 + NaN);
console.log(NaN + 1);
如果您想限制t他的JavaScript的许可行为,可以使用默认参数和/或抛自定义错误:
function add(a, b) {
a = a || 0;
b = b || 0;
return a + b;
}
var result = add(10);
console.log(result);
function add(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
if (isNaN(a) || isNaN(b)) {
throw new Error('NaN is not a number');
} else {
return a + b;
}
} else {
throw new Error('Invalid operands');
}
}
var result = add(10);
console.log(result);
钻营也可能是考虑:
function add(a) {
return function (b) {
return a + b;
};
}
console.log(add(10));
console.log(add(10)(3));
尝试'加( '10')'。 – RobG
well b未定义...你认为应该发生什么? – epascarello
@RobG为什么试着把它作为字符串传递,你仍然会在返回中得到'10undefined'因为没有第二个参数给出 – NewToJS