15-字符串连接
8.7 字符串连接
有时候,你可能希望把数组中元素的值通过一些分隔符连接起来。 Array.prototype.join
方法接收一个分隔符作为参数(在不指定的时候会用逗号作为默认值),返回一个连接了所有元素的字符串(包含未定义和删除的元素,这些元素会变成空数组、空元素、 undefined
、或空字符串):
const arr = [1, null, "hello", "world", true, undefined];
delete arr[3];
arr.join(); // "1,,hello,,true,"
arr.join(''); // "1hellotrue"
arr.join(' -- '); // "1 -- -- hello -- -- true --"
如果该方法用得够巧妙,结合字符串连接 Array.prototype.join
可以用来创建类似于HTML中 <ul>
的列表:
const attributes = ["Nimble", "Perceptive", "Generous"];
const html = '<ul><li>' + attributes.join('</li><li>') + '</li></ul>';
// html: "<ul><li>Nimble</li><li>Perceptive</li><li>Generous</li></ul>";
这里一定要注意,不要在空数组上调用这个方法:因为最终会得到一个空的 <li>
元素!