原來你是這樣的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的將來。

相關文章
相關標籤/搜索