2017-05-31 38 views
-1

为什么这个函数返回NaN?传递一个值减少功能我看到不匹配并返回NAN

function add(a, b) { 
 
    return a + b; 
 
} 
 
//add(10); 
 

 
var result = add(10); 
 

 
console.log(result);

+0

尝试'加( '10')'。 – RobG

+0

well b未定义...你认为应该发生什么? – epascarello

+0

@RobG为什么试着把它作为字符串传递,你仍然会在返回中得到'10undefined'因为没有第二个参数给出 – NewToJS

回答

2

b是不确定的,当你只能传递10的功能,因此10 + undefined是你回来的东西;所以NaN,又名不是数字。

0

function add(a, b) { 
 
    return a + b; 
 
} 
 
//add(10); 
 

 
var result = add(10,0); 
 
//change this 
 

 
console.log(result);

+0

欢迎来到SO。请阅读此[如何回答](http://stackoverflow.com/help/how-to-answer)以提供高质量的答案。只发布代码不是一个好答案。 – thewaywewere

1

这里的问题是,bundefined。因此,另外,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));