1. String(字符串)
String
?對象用于處理和操作文本數據。
length
:返回字符串的長度。
const str = "Hello";
console.log(str.length); // 輸出: 5
charAt(index)
:返回指定索引位置的字符。
const str = "Hello";
console.log(str.charAt(1)); // 輸出: e
concat(str1, str2, ...)
:連接多個字符串。
const str1 = "Hello";
const str2 = " World";
console.log(str1.concat(str2)); // 輸出: Hello World
toUpperCase()
?和?toLowerCase()
:將字符串轉換為大寫或小寫。
const str = "Hello";
console.log(str.toUpperCase()); // 輸出: HELLO
console.log(str.toLowerCase()); // 輸出: hello
indexOf(substring)
:返回子字符串在字符串中首次出現的位置,如果未找到則返回 -1。
const str = "Hello";
console.log(str.indexOf("l")); // 輸出: 2
2. Array(數組)
Array
?對象用于存儲多個值,這些值可以是不同的數據類型。
push(item1, item2, ...)
:在數組末尾添加一個或多個元素,并返回新的長度。
const arr = [1, 2, 3];
const newLength = arr.push(4);
console.log(arr); // 輸出: [1, 2, 3, 4]
console.log(newLength); // 輸出: 4
pop()
:移除并返回數組的最后一個元素。
const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(arr); // 輸出: [1, 2]
console.log(lastElement); // 輸出: 3
splice(start, deleteCount, item1, item2, ...)
:從數組中添加或刪除元素。
const arr = [1, 2, 3, 4];
arr.splice(1, 2, 5, 6);
console.log(arr); // 輸出: [1, 5, 6, 4]
join(separator)
:將數組元素連接成一個字符串。
const arr = [1, 2, 3];
console.log(arr.join("-")); // 輸出: 1-2-3
map(callback)
:創建一個新數組,其結果是該數組中的每個元素都調用一個提供的函數后返回的結果。
const arr = [1, 2, 3];
const newArr = arr.map(item => item * 2);
console.log(newArr); // 輸出: [2, 4, 6]
3. Date(日期)
Date
?對象用于處理日期和時間。
- 創建日期對象:
const now = new Date(); // 當前日期和時間
const specificDate = new Date("2025-04-21"); // 指定日期
getFullYear()
:返回年份。
const date = new Date();
console.log(date.getFullYear()); // 輸出當前年份
getMonth()
:返回月份(0 - 11,0 表示一月)。
const date = new Date();
console.log(date.getMonth()); // 輸出當前月份
getDate()
:返回日期(1 - 31)。
const date = new Date();
console.log(date.getDate()); // 輸出當前日期
toLocaleString()
:將日期轉換為本地字符串表示。
const date = new Date();
console.log(date.toLocaleString()); // 輸出本地日期和時間字符串
4. Math(數學)
Math
?是一個內置對象,它擁有一些數學常數和函數。
Math.PI
:圓周率。
console.log(Math.PI); // 輸出: 3.141592653589793
Math.random()
:返回一個介于 0(包含)和 1(不包含)之間的隨機數。
console.log(Math.random()); // 輸出一個隨機數
Math.floor(x)
:返回小于或等于 x 的最大整數。
console.log(Math.floor(3.9)); // 輸出: 3
Math.ceil(x)
:返回大于或等于 x 的最小整數。
console.log(Math.ceil(3.1)); // 輸出: 4
Math.max(x1, x2, ...)
?和?Math.min(x1, x2, ...)
:返回一組數中的最大值和最小值。
console.log(Math.max(1, 2, 3)); // 輸出: 3
console.log(Math.min(1, 2, 3)); // 輸出: 1