如何清空字符串数组中的字符串,但保留数组的长度

Qii*_*iia 1 javascript arrays string

我有一个 JavaScript 字符串数组:

array = ['xx', 'xxxxxxxx', 'xxx'];
Run Code Online (Sandbox Code Playgroud)

我想达到这个目标:

 array = ['', '', '']; //empty the strings but keep the length of array
Run Code Online (Sandbox Code Playgroud)

什么是最好的方法?

LMD*_*LMD 7

使用Array.fill

array = ['xx', 'xxxxxxxx', 'xxx'];
array.fill('');
console.log(array)
Run Code Online (Sandbox Code Playgroud)

如果需要创建新数组,请Array结合使用构造函数Array.fill

array = ['xx', 'xxxxxxxx', 'xxx'];
const newArray = new Array(array.length);
newArray.fill('');
console.log(newArray)
Run Code Online (Sandbox Code Playgroud)