2014-09-30 153 views
0

为什么if语句在底部计算上不正确?console.log作为if语句中的条件

是否可能不能使用console.log作为if语句中的条件以及数字?

// This is what a function looks like: 

var divideByThree = function (number) { 
    var val = number/3; 
    console.log(val); 
}; 

// On line 12, we call the function by name 
// Here, it is called 'dividebythree' 
// We tell the computer what the number input is (i.e. 6) 
// The computer then runs the code inside the function! 
divideByThree(6); 

if (divideByThree(6) === 2) 
{console.log("I'm right")} 
else 
{console.log("I'm stupid")} 

这肯定工程

var divideByThree = 2; 

if (divideByThree === 2) 
{console.log("I'm right no.2")} 
else 
{console.log("I'm stupid no.2")} 
+1

可能的重复:http://stackoverflow.com/questions/24439380/javascript-use-of-varia bles-basic-functions – 2014-09-30 10:35:48

+0

你没有返回divideByThree的结果,所以它会反弹undefined,这不等于2 – mfarouk 2014-09-30 10:39:19

回答

0

不必返回divideByThree的结果,所以它会retrun不确定这是不是等于2

编辑 添加返回功能

var divideByThree = function (number) { 
    var val = number/3; 
    console.log(val); 
    return val; 
}; 
+0

你的意思是通过使用“divideByThree(6);”我不是返回divideByThree的结果,而是返回divideByThree结果的console.log?如果是,我将如何返回结果或表达式如何计算为真? – nearmint 2014-09-30 10:42:34

+0

只需在函数中加入return语句,回答编辑 – mfarouk 2014-09-30 10:47:27

+0

谢谢!我想我不能用console.log来打印控制台以外的任何东西,这很有道理。 – nearmint 2014-09-30 10:50:57