简体   繁体   English

为什么这个 function 中的 return 语句会引发错误?

[英]Why does return statement in this function throws an error?

I have a function that tests if the passed value is an object.我有一个 function 来测试传递的值是否是 object。 If the passed value is an object, I want to console.log the value.如果传递的值是 object,我想 console.log 值。 Else, I want to return false.否则,我想返回 false。 However, I got an syntax error stating that invalid return statement is used in the console.但是,我收到一个语法错误,指出控制台中使用了无效的 return 语句。 Here is the code:这是代码:

function a(value){
  typeof value === 'object'?console.log(value):return false;
}
a({});

Any help will be apreciated.任何帮助将不胜感激。

Statement cannot be used as an expression语句不能用作表达式

return is a statement return是一个语句

?: requires an expression ?:需要一个表达式

function a(value){
  return typeof value === 'object' ? console.log(value) : false;
}
a({});

This is an inappropriate use of the conditional operator.这是对条件运算符的不当使用。 Use it when you're selecting different values, not actions.当您选择不同的值而不是操作时使用它。 Choose between statements with if .在带有if的语句之间进行选择。

function a(value) {
    if (typeof value == 'object') {
        console.log(value);
    } else {
        return false;
    }
}

console.log() doesn't return a value, so there's little point in using it in a conditional operator. console.log()不返回值,因此在条件运算符中使用它几乎没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM