I have an array of strings in 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 = ['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 = ['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.
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.
let array = ['xx', 'xxxxxxxx', 'xxx']; const emptyArr = array.map((item)=>""); console.log(emptyArr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.