简体   繁体   English

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

[英]How to empty the strings in an array of strings, but keep the length of array

I have an array of strings in javaScript:我在 javaScript 中有一个字符串数组:

array = ['xx', 'xxxxxxxx', 'xxx'];

I want to reach this:我想达到这个:

 array = ['', '', '']; //empty the strings but keep the length of array

What is the best way?什么是最好的方法?

Use Array.fill .使用Array.fill

 array = ['xx', 'xxxxxxxx', 'xxx']; array.fill(''); console.log(array)

If you need to create a new array, use the Array constructor combined with Array.fill :如果您需要创建一个新数组,请使用Array构造函数与Array.fill结合使用:

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

use.map method to remove content and return the empty string.使用.map 方法删除内容并返回空字符串。

 array = ['xx', 'xxxxxxxx', 'xxx']; const newArray = array.map(data=> ("")); console.log(newArray)

array = array.map(function(item){return '';});

Use .map() method for immutability of original array.使用.map()方法来保证原始数组的不变性。

 let array = ['xx', 'xxxxxxxx', 'xxx']; const emptyArr = array.map((item)=>""); console.log(emptyArr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM