二、原始字符串與 String 對象
在 JavaScript 中,字符串有兩種形式:
原始字符串(Primitive String):直接用字面量聲明,如 "abc"。
String 對象(String Object):通過 new String("abc") 創(chuàng)建。
示例:
代碼高亮:
let str1 = "abc"; // 原始字符串
let str2 = new String("abc"); // 字符串對象
它們的區(qū)別:

可以看到,雖然兩者內(nèi)部的字符串值相同,但 new String 創(chuàng)建的是對象類型,容易在邏輯判斷中出錯:
if (new String("")) console.log("執(zhí)行"); // 會執(zhí)行,因為對象永遠(yuǎn) truthy
if ("") console.log("執(zhí)行"); // 不會執(zhí)行
建議:除非做語言機制實驗,否則使用原始字符串即可。
三、字符串的屬性與方法
1. length 屬性
原始字符串雖然不是對象,但在訪問屬性或方法時,JavaScript 會自動裝箱,臨時把原始字符串包裝成 String 對象:
let str = "hello";
console.log(str.length); // 5
這個機制也適用于調(diào)用方法,例如:
console.log("abc".toUpperCase()); // "ABC"
2. 常用方法
代碼高亮:
str.charAt(0); // 返回第一個字符
str.includes("he"); // 判斷是否包含
str.startsWith("he"); // 是否以指定字符串開頭
str.endsWith("lo"); // 是否以指定字符串結(jié)尾
str.indexOf("l"); // 第一次出現(xiàn)位置
str.lastIndexOf("l"); // 最后一次出現(xiàn)位置
str.slice(0, 3); // "hel" 支持負(fù)數(shù)
str.substring(0, 3); // "hel" 不支持負(fù)數(shù)
str.split(" "); // ["hello", "world"]
str.toUpperCase(); // "HELLO"
str.toLowerCase(); // "hello"
str.replace("hello", "hi"); // 替換一次
str.replaceAll("l", "*"); // 替換全部
代碼高亮:
str.trim(); // 去頭尾空格
str.trimStart(); // 去開頭空格
str.trimEnd(); // 去尾部空格
"5".padStart(3, "0"); // "005"
"5".padEnd(3, "0"); // "500"
"abc".repeat(3); // "abcabcabc"
四、數(shù)組的 map 方法
數(shù)組是 JavaScript 中另一類常用數(shù)據(jù)結(jié)構(gòu),map 是最重要的方法之一。它遍歷數(shù)組的每個元素,并返回由每次回調(diào)函數(shù)返回值組成的新數(shù)組。
示例:
const todos = [
{ id: 1, text: '學(xué)習(xí)es6' },
{ id: 2, text: '通讀你不知道的JavaScript' }
];
const liList = todos.map(todo => `<li>${todo.text}</li>`);
console.log(liList);
// ["<li>學(xué)習(xí)es6</li>", "<li>通讀你不知道的JavaScript</li>"]
注意:
todos.map(todo => `<li>${todo.text}</li>`);
?
代碼高亮:
const todosEL = document.querySelector('.todos');
todosEL.innerHTML = `
<ul>
${todos.map(todo => `<li>${todo.text}</li>`).join('')}
</ul>
`;