原来你是这样的else if ?

前言

最近几年一直以JavaScript最为第一语言开发,所以死扣JavaScript,突然发现else if原来不是我想象中的else if。并对自己之前的无知感到羞愧。

写过的都知道在写if条件语句的时候都会写成else if,而不是写成elseif

为啥中间要有空格呢?

再看看Python会写成elifPHP写成elseif、Lua写成elseif

经常在代码中出现的样子

if条件语句是每个人的代码中都会出现的。他们大概是这样的

function testNum(a) {
  if (a > 0) {
    return "positive";
  } else {
    return "NOT positive";
  }
}

console.log(testNum(-5));
// expected output: "NOT positive"
复制代码

或者是这样的

if (x > 5) {
 /* do the right thing */
} else if (x > 50) {
 /* do the right thing */
} else if (x > 100) {
 /* do the right thing */
} else {
 /* do the right thing */
}
复制代码

那么重点来了,JavaScript是 没有 else if语句的。

啥 ? 那我用的到底是什么。。。

不得不说的代码块

我们有时候会这么写if

if(a) dosomething(a)
复制代码

很多JavaScript代码检查工具会建议应该加上{...}

if(a) {dosomething(a)}
复制代码

同样对于else,在只包含单条语句的时候可以省略代码块。

所以实际上,上面的else if代码全貌实际是这样的

if (x > 5) {
 /* do the right thing */
} else {
  if (x > 50) {
   /* do the right thing */
  } else {
    if(x > 100 ){
      /* do the right thing */
    }else{
      /* do the right thing */
    }
  }
}
复制代码

当我们去掉else{...}

if (x > 5) {
 /* do the right thing */
} else
  if (x > 50) {
   /* do the right thing */
  } else
    if(x > 100 ){
      /* do the right thing */
    }else{
      /* do the right thing */
    }
复制代码

然后再把 else 和 if 弄到一行。

if (x > 5) {
 /* do the right thing */
} else if (x > 50) {
   /* do the right thing */
} else if(x > 100 ){
  /* do the right thing */
}else{
  /* do the right thing */
}
复制代码

就是我们经常写的else if

所以换句话说,else if其实只是else里面单独的if语句,去掉了{...},并省略了一层代码缩进。

可能是开发者们发明的用法,而这并不是JavaScript语法的范畴。

多说两句

{...}大括号,不仅仅只是大括号。我们在很单纯的使用大括号的时候,大概是:

定义一个对象字面量

var foo = {
  key: 1,
  value: bar()
}
复制代码

我们把大括号赋值给了一个变量foo,所以现在{...}是一个值。

打上一个label

当我把var foo =去掉,单纯的剩下一个{...}

{
  foo:bar()
}
复制代码

ps:这种写法在JavaScript不常见,但他又是完全合法的。

{...}在这里只是一个普通的代码块。那么里面的foo:bar()是什么呢?

这种写法是不提倡的写法,也是JavaScript不常用的特性,叫“标签语法”。换句话说,给一条语句加上标签,可以配合break / continue来实现goto的效果。

foo: {
  console.log('face');
  break foo;
  console.log('this will not be executed');
}
console.log('swap');

// this will log:

// "face"
// "swap
复制代码

上面这个例子就是用break,终止掉了foo标签对应的语句。所以控制台看到的只有

// "face"
// "swap
复制代码

有兴趣的同学可以去MDN查阅developer.mozilla.org/zh-CN/docs/…

other

{...}与let一起使用的时候就特别有用了,可以强制劫持块的作用域。

{
  console.log(bar); //ReferenceError: bar is not defined
  let bar = 'webkong'
  console.log(bar); // webkong
}
console.log(bar) //ReferenceError: bar is not defined
复制代码

最后

有人会说,java也是写else if呢...,go好像也是呢? 那我不管,我只想写JS。

回顾这几年,后悔没有给JavaScript足够的耐心和时间,把她当成一门真正的编程语言来探索和学习。很多人可能跟我一样,最开始使用她,用的多了,才开始的回过头来学习。JavaScript是一门优秀的语言,她有简单易用的语法,同时语言机制又十分复杂和微妙。用起来很容易,但全面掌握规则却很难。随着ES标准的不断演进,概念语法上面的不断发展,我很期待JavaScript的未来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值