[英]How to empty the strings in an array of strings, but keep the length of array
我在 javaScript 中有一个字符串数组:
array = ['xx', 'xxxxxxxx', 'xxx'];
我想达到这个:
array = ['', '', '']; //empty the strings but keep the length of array
什么是最好的方法?
使用Array.fill
。
array = ['xx', 'xxxxxxxx', 'xxx']; array.fill(''); console.log(array)
如果您需要创建一个新数组,请使用Array
构造函数与Array.fill
结合使用:
array = ['xx', 'xxxxxxxx', 'xxx']; const newArray = new Array(array.length); newArray.fill(''); console.log(newArray)
使用.map 方法删除内容并返回空字符串。
array = ['xx', 'xxxxxxxx', 'xxx']; const newArray = array.map(data=> ("")); console.log(newArray)
array = array.map(function(item){return '';});
使用.map()
方法来保证原始数组的不变性。
let array = ['xx', 'xxxxxxxx', 'xxx']; const emptyArr = array.map((item)=>""); console.log(emptyArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.