JavaScript 中将数组转换为不带逗号的字符串
要将数组转换为不带逗号的字符串,请调用数组的 join() 方法,将空字符串作为参数传递给它 – arr.join(”) 。 join 方法返回一个字符串,其中包含由提供的分隔符连接的所有数组元素。
const arr = ['one', 'two', 'three'];
const withoutCommas = arr.join('');
console.log(withoutCommas); // ?️ 'onetwothree'
console.log(typeof withoutCommas); // ?️ string
我们传递给 Array.join 方法的唯一参数是一个分隔符。
该方法返回一个字符串,其中包含由提供的分隔符连接的所有数组元素。
如果我们的用例要求您连接具有不同字符的数组元素,请将字符作为参数传递给 join() 方法。
const arr = ['one', 'two', 'three'];
const withSpaces = arr.join(' ');
console.log(withSpaces); // ?️ 'one two three'
const withDashes = arr.join('-');
console.log(withDashes); // ?️ 'one-two-three'
const withCommaAndSpace = arr.join(', ');
console.log(withCommaAndSpace); // ?️ 'one, two, three'
如果对空数组调用 join 方法,将返回一个空字符串。
console.log([].join('')); // ?️ ''
如果数组包含未定义的元素、null 或空数组 [],它们将被转换为空字符串。
console.log(['a', 'b', null].join('')); // ?️ 'ab'
对于大多数用例,此行为非常有效。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。