[JS] JavaScript 運算子(Operator)
運算式與運算子 @ MDN
[TOC]
條件判斷(conditional statement)
- 物件(object): 都是 true(空物件也是 true)
- 陣列(array):陣列是一種物件,因此都會是 true(空陣列
[]
也是 true) - Undefined: 是 false
- Null:是 false
- 布林(Booleans):會根據 Boolean 值回
- 數值(Numbers):除了
0
, orNaN
會是 false 外,其他都是 true - 字串(String):除了空字串
''
會是 false 之外,其他都是 true(字串中有空格也是 true)
code style
// 單行的 if 可以不用加上 {...}
if (lemons) console.log('hello');
16.1 Use braces with all multi-line blocks @ airbnb
- 不要在
else
中使用return
:
16.3 no-else-return @ airbnb
// bad
function foo() {
if (x) {
return x;
} else {
return y;
}
}
// good
function foo() {
if (x) {
return x;
}
return y;
}
// bad
function cats() {
if (x) {
return x;
} else if (y) {
return y;
}
}
// good
function cats() {
if (x) {
return x;
}
if (y) {
return y;
}
}
- 當
if
當中的條件式太長的時候,可以換行並把比較運算子放在最前面(17.1 @ airbnb):
// good
if (foo === 123 && bar === 'abc') {
thing1();
}
// good
if (
(foo === 123 || bar === 'abc') &&
doesItLookGoodWhenItBecomesThatLong() &&
isThisReallyHappening()
) {
thing1();
}
// good
if (foo === 123 && bar === 'abc') {
thing1();
}
比較運算子(comparison operator)
- 使用
===
或!==
其餘參數(rest parameter)
其餘運算字會幫助 我們把輸入函式中的參數值變成陣列的形式(多個值 => 陣列):
let avg = function (...arr) {
console.log(arr); // [1,3,5,7,9]
};
console.log(avg(1, 3, 5, 7, 9));
展開語法(spread syntax)
展開運算子則是可以把陣列中的元素取出(陣列 => 多個值):
複製陣列(Copy an array)
var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()
arr2.push(4);
// arr2 becomes [1, 2, 3, 4]
// arr remains unaffected
連結陣列(concatenate arrays)
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; // [ 0, 1, 2, 3, 4, 5 ]