一句話概括兩者的差別:字符串本質上是一串字符,而數組是一個容器,裡面可以裝數字、字符、對象,甚至另一個數組。理解這個起點,後面的方法列表就好懂了。
var str = "liuzhanqi";
document.write(str["length"]); // 等價於 str.length
document.write(str.length);
var s = String.fromCharCode(72, 101, 108, 108, 111, 33);
document.write(s); // 把各整數當作 Unicode 編碼,拼接成字符串
document.write("liu".localeCompare("zhan")); // 依系統預設規則比較兩段字符串
document.write("liu".slice(1)); // 擷取子字符串
document.writeln("se nki".split(' ')); // 以分隔符切開,回傳一個數組
document.write('liu'.fontcolor('red'));
document.write('liu'.fixed()); // 以等寬字顯示
document.write('liu'.strike()); // 加上刪除線
document.write("senki".sub()); // 顯示為下標
document.write("senki".sup()); // 顯示為上標
charCodeAt(index):回傳指定位置字符的 Unicode 編碼,取值落在 0~65535 之間;若 index 超出範圍,結果是 NaN。
concat(str2):把 str2 接到原字符串後面,產生一個全新的字符串。原字符串不會被改動。
charAt(index):取出 index 位置上的一個字符。
anchor(name):建立一個錨點,常用於頁內跳轉。
link(url):把字符串包裝成超鏈接。
順帶一提,上面那些 fontcolor、fixed、strike、sub、sup 之類的方法屬於早期的表現層 API,如今更推薦用 CSS 來控制樣式,行內標籤式的做法只適合在極簡場景或 historic 代碼裡出現。
把字符串和數組放在一起看,最大的收穫是:字符串的很多方法(例如 split)會回傳數組,而數組的 join 又能把成員合回字符串。兩者之間的轉換,正是日常處理文本時最常用的套路。有不清楚的地方歡迎留言,一起把基礎打牢。