Javascript - 運算子與型別
運算順序
先運算完再指定
i = 1
//賦值
i += 1
// i = i+1
-=
// i = i-1
/=
// i = i /
*=
//i = i*
%=
//餘數
等號位置的差異
let i = 1, b
b = i--
//b = 1 , i = 0
//先執行b=i,再執行i = i-1
b = --i
//先執行i = i-1 再執行z=i
// b = 0, i = 0
型別
原始型別:六種
- Boolean, Null, Undefined, Number, BigInt, String, Symbol
- 都是原始定義的值,不能被改變
- Boolean: true/false
- Null: 只有Null
- Undefined:還沒被定義的變數,例如
let num
console.log(typeof (num))
- Number:一般的數字再加上
+Infinity
、-Infinity
、NaN
- String:文字資料
- Symbol
Symbol("foo") === Symbol("foo"); // false
const sym = new Symbol(); // TypeError
const sym = Symbol("foo");
typeof sym; // "symbol"
const symObj = Object(sym);
typeof symObj; // "object"
非原始型別:Object
- function, array,...等等都包含在內
- 特性:可以自由新增屬性
console.log(typeof True) //boolean
console.log(typeof "123")//string
console.log(typeof 1) //number
console.log(typeof 123n) //bigint
console.log(typeof []) //object
console.log(typeof null) //object
//但原始型別為null
console.log(typeof function() {}) //function
//但原始型別為object
const obj = {}
obj.name = 'hello'
console.log(obj.name) //hello
new
使用new會讓型別成為object
例如
const string1 = "abc"
console.log(typeof string1)//string
console.log(typeof "abc") //string
const string2 = new String("xyz")
console.log(typeof string2) //object
型別轉換
顯性轉換
常見:字串轉數字 Number()或運算子
console.log(+"1") //1
console.log(+true) //1
console.log(!0) //true
console.log(!!0) //false
console.log(!1) //false
數字轉字串 toString()
轉布林 Boolean()
console.log(!0) //true
console.log(!!0) //false
console.log(!1) //false
隱性轉換
- 有一個是字串=>都變字串
- 有一個非原始型別=>當字串
- true會被視為1,false視為0
num+str
//str
str+str
//str
console.log(1+true) //2
console.log(String([1,2])) //1,2
console.log("1"+2) //12 加號在有string的情況下會當成string拼接
console.log("1"-2) //-1 遇到-號會試著轉換成數字
console.log(1+[2]) //12
console.log(1+[1,2]) //11,2
console.log(1-[1,2]) //NaN
console.log("12"+true) //12true
console.log(1 +{}) //1[object Object]
console.log(String({})) //[object Object]
note:
- Bigint(n)可以彼此運算但跟一般型別混和會錯誤
- Symbol不能運算
型別比較('==' '===')
寬鬆比較
- 物件與物件相比=>false
- 物件vs非物件 =>先string在Number
- 大部分會轉成number, string或boolean做比較
- ture=>1 / false=>0
- null=>false
- undefined=>false
console.log(1==true) //true
console.log(3 == true) //false
console.log(null == undefined) //true
console.log(0 == undefined) //false
console.log(1==1n) //true
console.log({} == []) //false
console.log({} == '[object Object]') //T
//先轉成數字
console.log(Number([])) //0
console.log(Number([1])) //1
console.log(Number([1,2])) //NaN
console.log([] == 0) //T
console.log([1] == 1) //T
console.log([1,2] == 12) //F
console.log([] == "0") //F
//物件相比
var numObj = new Number('13456') //object
var num = Number('13456') //number
numObj === 13456 //False
num === 13456 //True
console.log(new Number(1) ==new Number(1)) //false
console.log({} ==={} ) //F
console.log([] ===[] ) //F
https://www.youtube.com/watch?v=kX3madakVl0
Comments