在JavaScript中,資料型別主要分為基礎型別 與 物件型別。
可以表示整數與浮點數。
常見數值運算:+、-、*、/、%、**、++、--、+= 等等。
let x = 10;
x++; // 11
x--; // 9
x /= 2 // 5
Number("20"); // 20
parseInt("10"); // 10
parseInt("1.23"); // 1
parseFloat("1.23"); // 1.23
+"20"; // 20 (一元 + 轉型數字)
typeof NaN; //"number"
Number("abc"); //NaN
let pi = 3.14159;
pi.toFixed(2); //"3.14"
pi.toString(); //"3.14159"
用單引號 ' ' 或雙引號 " " 包起來。
串接使用 + 或字串模板 (ES6):
let name = "Spark";
let intro = `Hello, my name is ${name}`;
String(123); //"123"
2021 + ""; //"2021"
let str = "Wilson";
str.length; // 6
str.slice(2,5); // "lso"
str.indexOf("son"); // 3
str.toUpperCase(); // "WILSON"
"Hello world".split(" "); // ["Hello","world"]
只有 true 與 false。
常用於條件判斷:
if (x > 10) { ... }
Boolean("hello"); // true
Boolean(""); // false
Boolean(0); // false
Boolean(123); // true
typeof null === "object"
是一個歷史 bug。變數被宣告但未賦值時,預設為 undefined。
let x;
console.log(x); // undefined
console.log(y); // ReferenceError: y is not defined
let big = 123456789012345678901234567890n;
obj.key
或 obj["key"]
。
let person = {
name: "Peter",
score: 100,
father: { name: "Nick" }
};
console.log(person.name); // "Peter"
console.log(person.father.name); // "Nick"
typeof []
回傳 "object",可以用 Array.isArray(arr)
確認是否為陣列。let arr = [1, "hi", true];
console.log(arr[0]); // 1
function sayHi(name) {
console.log(`Hi ${name}`);
}
sayHi("Wilson");
typeof "hello"; // "string"
typeof 100; // "number"
typeof true; // "boolean"
typeof {}; // "object"
typeof []; // "object"
typeof function(){}; // "function"
typeof undefined; // "undefined"
typeof null; // "object" (bug)