從例子中看"短路求值(Short-circuit evaluation)"(又稱: 最小化求值)

維基百科中這麼說:

短路求值(Short-circuit evaluation,又稱最小化求值),是一種邏輯運算符的求值策略。只有當第一個運算數的值無法確定邏輯運算的結果時,才對第二個運算數進行求值。

以下先舉個看到的例子,

想做的功能: 如果有輸入關鍵字, 則自動勾選到相對應的checkbox

完整code如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<h2>根據指定內容勾選Checkbox</h2>
<p>如果內容中含有關鍵字:「JavaScript」、「小亮」、「遊戲」, 則對應的關鍵字核取方塊會被勾選</p>
<textarea id="contentCheckbox" data-target="autoKeywordSelect">

</textarea>
<br>
<input type="checkbox" name="autoKeywordSelect" data-k="JavaScript">JavaScript<br>
<input type="checkbox" name="autoKeywordSelect" data-k="小亮">小亮<br>
<input type="checkbox" name="autoKeywordSelect" data-k="遊戲">遊戲<br>

<script>

window.onload = function() {

var contentCheckbox = document.getElementById("contentCheckbox"),
_targets = document.getElementsByName(contentCheckbox.getAttribute("data-target")),
targetsLen = _targets.length,
i = 0;

contentCheckbox.onkeyup = function() {

for (i = 0; i < targetsLen; i++) {

var _t = _targets[i],
       _v = this.value;

/*
三元運算式寫法:
_v.search(_t.getAttribute("data-k")) != -1 ?
_t.ckecked = true :
_t.checked = false;
*/

//單鏈式寫法:
_t.checked = _v.search(_t.getAttribute("data-k")) != -1 && true || false;

}

};

};

</script>
</body>
</html>


從例子中可看見用"單鏈式寫法"是較乾淨的寫法,

因而現在需要看看短路求值的內容,

Logical Operators:
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/Logical_Operators

擷取重點如下:


Short-circuit evaluation:

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

1. false && (anything) is short-circuit evaluated to false.

2. true || (anything) is short-circuit evaluated to true.

注意: the anything part of the above expression is any single logical expression (as indicated by the parentheses).

e.g. the following two functions are equivalent:

這個:

function shortCircuitEvaluation() {

  doSomething() || doSomethingElse()

}

相等於:

function equivalentEvaluation() {

  var flag = doSomething();
  if (!flag) {

    doSomethingElse();

  }

}


However, the following expressions are not equivalent due to operator precedence:

e.g.

1. false && true  || true                          // returns true

2. false && (true || true)                       // returns false



接著來看"Conversion rules":

A. Converting AND to OR:

bCondition1 && bCondition2

相等於:

!(!bCondition1 || !bCondition2)


B. Converting OR to AND:

bCondition1 || bCondition2

相等於:

!(!bCondition1 && !bCondition2)


C. Converting between NOTs:

!!bCondition

相等於:

bCondition


最後, 看看"Removing nested parentheses":

A. Removing nested AND:

bCondition1 || (bCondition2 && bCondition3)

相等於:

bCondition1 || bCondition2 && bCondition3


B. Removing nested OR:

bCondition1 && (bCondition2 || bCondition3)

相等於:

!(!bCondition1 || !bCondition2 && !bCondition3)



留言

熱門文章