原来你是这样的else if ?

前言

最近几年一直以JavaScript最为第一语言开发,因此死扣JavaScript,忽然发现else if原来不是我想象中的else if。并对本身以前的无知感到羞愧。java

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

为啥中间要有空格呢?编程

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

常常在代码中出现的样子

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语句的。学习

啥 ? 那我用的究竟是什么。。。ui

不得不说的代码块

咱们有时候会这么写ifthis

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

不少JavaScript代码检查工具会建议应该加上{...}spa

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的将来。

相关文章
相关标签/搜索