動態型別(Dynamic Typing)/ 純值(Primitive Type)/ 運算子(Operator)/ 運算子優先性(Operator Precedence)/ 相依性(Associativity)/ 強制型轉(Coercion) / 預設值(Default value)
動態型別(Dynamic Typing)
You don’t tell the engine what type of data a variable holds, it figures it out while your code is runnung
Variable can hold different types of values because it’s all figured out during execution.
不用告訴JavaScript變數是何種型別的資料,它會在運行程式時自動知道。
一變數可以在不同時候擁有不同型別,因為型別都是在執行時才知道的。
純值(Primitive Type)
A type of data that represents a single value
That is, not an object.
- Undefined: JS給所有變數的初始值,直到你給定變數一個值,你不應該用它來設定值。
- null: 也表不存在,所以別用 undefined 可以用 null
- Boolean
- number: 浮點數,一定永遠有小數點跟在後面
- string
- symbol
運算子(Operator)
A special function that is syntactically(written) differently
Generally, operators take two parameters and return one result.
運算子都是函數。
運算子優先性(Operator Precedence)
Which operator function gets called first
Functions are called in order of precedence (HIGHER precedence wins).
哪個運算子被優先運算,具有高優先性的運算子會先計算。
相依性(Associaticvity)
What order operator functions get called in: LEFT-TO-RIGHT or RIGHT-TO-LEFT
When functions have the same precedence.
運算子被計算的順序,左相依性/右相依性,如果全部的運算子優先性都相同,這時就要看相依性。
var a=2, b=3, c=4;a= b= c;console.log(a, b, c) //4, 4, 4優先性相同,故以相依性判斷,=是由右至左
強制型轉(Coercion)
Converting a value from one type to another.
This happens quite often in JavaScript because it’s dynamically typed.
強制型轉,轉換一個值的型別。
var a = 1+ ‘2’ //1被強制轉換成'1'console.log(a)=’12'
比較運算子
console.log(3 < 2 < 1) = true !!!!!因為運算子都相同所以優先性相同因此依相依性判斷,<是左相依性,因此由最左兩的開始判斷3 < 2 falseconsole.log(false < 1)而false型轉後=0 //Number(false) = 00 < 1 true因此 console.log(3 < 2 < 1) = true
盡量使用===來進行比較,以避免型轉的問題!!
存在與布林
if()條件函式會強制將()內轉換為Boolean
null, undefined, false, '', 0 都會被判斷為false
預設值(Default value)
*ES6有其他的設定方式
function greet(name) {
name = name || ‘<Your name here>’; //預設值
console.log(‘Hello ‘ + name);}
- greet() 的情況:‘Hello <Your name here>'
||層級高於 = ,因此先由name || ‘<Your name here>’開始運算
會回傳 ‘<Your name here>’,因為name是undefined屬false而字串是true
此時再執行name=‘<Your name here>’。
2. greet( 'Tony' ) 的情況:‘Hello Tony’
將 ’Tony’代入name,而'Tony' || ‘<Your name here>’兩個都是true,會回傳第一個true也就是name,也就是 'Tony' ,而此時再執行name='Tony'。
*需注意當值帶入0時也會被判斷為false屬於特例