JS equivalent to Ruby's return if

问题: In Ruby i can use return if variable != 1 as example to not run the code comming after the return. I need to do the same in JS but i dont want to use a full if (variable !=...

问题:

In Ruby i can use return if variable != 1 as example to not run the code comming after the return. I need to do the same in JS but i dont want to use a full if (variable != 1) { My code here } statement. Is that possible?


回答1:

Put the return after the if statement:

if (variable != 1) return;
// more code here

回答2:

Put return after a one-line if:

if (variable !== 1) return;

Demonstration:

function test() {
  if (variable != 1) return;
  console.log("Variable equals one"); //Will never be run
}

var variable = 2;
test();


回答3:

1.

if (i !== 1) return 'True';

2.

return (i !== 1) ? 'True' : 'False';

3.

if (i !== 1) { console.log('Not equal'); } // else { }

Example

function test() {
    let i = 1;
    if (i !== 1) {
        console.log('Not equal to 1');
        return false;
    } else {
        return true;
    }
}

console.log(test());

Single

function test() {
    let i = 1;
    if (i !== 1) return 'True';
}

console.log(test());

Ternary operator

function test() {
    let i = 1;
    return (i !== 1) ? 'True' : 'False';
}

console.log(test());

  • 发表于 2019-03-18 18:30
  • 阅读 ( 187 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除