JS基礎-變數型別和計算
阿新 • • 發佈:2021-10-27
一、變數型別
值型別vs引用型別
先來看以下兩個栗子
// 值型別 let a = 100; let b = a; a = 200 console.log('b',b); // 100
// 引用型別 let a = {age: 20}; let b = a; b.age = 21 console.log('a.age',a.age); // 21
思考一下:為什麼慄1打印出來的是100,而慄2打印出來的是21呢?
深入分析:
棧是存放變數的地方,栗子1首先定義一個變數a等於100,然後定義一個變數b等於a,b等於100,再將a的值改為200,可以看到b的值沒有改變,因為b和a是不一樣的
棧和堆是同時存在的,栗子2首先定義一個變數a等於一個物件{age: 20},這時候堆會生成一個記憶體地址1,value等於{age: 20},而棧中的a實際指向的是記憶體地址1,然後定義一個變數b等於a,b賦值的是a的記憶體地址1,然後將b.age賦值為21,實際也是將記憶體地址1的value改為{age: 21},這時候再去訪問a.age,也為21
常見值型別:
let a; //undefined const str = 'abc'; const n = 100; const b = true; const s = Symbol('s');
常見引用型別:
const obj = {x: 100}; const arr = ['a','b','c']; const n = null; //特殊引用型別,指標指向空地址 function fn() {}; //特殊引用型別,但不用於儲存資料,所以沒有“拷貝,複製函式”這一說
typeof運算子
// 識別所有值型別 let a; typeof a //'undefined'const str = 'abc'; typeof str //'string' const n = 100; typeof n //'number' const b = true; typeof b // 'boolean' const s = Symbol('s'); typeof s //'symbol'
// 能判斷函式 typeof console.log() // 'function' typeof function () {} // 'function' // 能識別引用型別(不能再繼續識別) typeof null // 'object' typeof['a','b','c'] // 'object' typeof {x: 100} // 'object'
二、變數計算-型別轉換
字串拼接
const a = 100 + 10 // '110' const b = 100 + '10' // '10010' const c = true + '10' // 'true10'
==運算子
它會盡量嘗試讓它們轉換之後去相等
100 == '100' // true 0 == '' // true 0 == false // true false == '' // true null == undefined // true // 除了==null外,其他一律用===,例如: const obj = {x: 100} if(obj.x == null) {} //相當於 if(obj.x === null || obj.x === undefined) {}
if語句和運算邏輯
truly變數:!!a === true的變數
falsely變數:!!a === false的變數
// 以下是falsely變數,其餘都是truly變數 !!0 === false !!NaN === false !!null === false !!undefined === false !!false === false
if語句
// truly 變數 const a = true if(a) { // ... } const b = 100 if(b) { // ... } //falsely 變數 const c = '' if(c) { // ... } const d = null if(d) { // ... } const e if(e) { // ... }
邏輯判斷
console.log(10 && 0); // 0 console.log('' || 'abc'); // 'abc' console.log(!window.abc); // true
思考一下:為什麼返回值是這樣的?
console.log(10 && 0); // 因為10是truly變數,所以繼續判斷返回第二個值 console.log('' || 'abc'); // 因為''是falsely變數,所以繼續判斷返回第二個值 console.log(!window.abc); // 因為!是非,直接取反 // 如果返過來console.log(0 && 10); // 0 因為0是falsely變數,直接返回(&&的運算規則是這樣) // console.log('abc' || ''); // 'abc' 因為'abc'是truly變數,直接返回(||的運算規則是這樣)