JS removes empty strings, undefined, null from arrays

JS removes empty strings, undefined, null from arrays

Method 1: traverse

	let arr=[原数组]
	let newArr= []
	// 方法1
	arr.forEach(item => {
	  if (item) {
	    newArr.push(item)
	  }
	})
	// 方法2
	for (let item of arr) {
	 if (item) {
	   newArr.push(item)
	 }
	}
	console.log(newArr)
    

Method 2: filter

	var arr = [原数组]
	var newArr = arr.filter(item => item && item.trim())
	console.log(newArr)

js array removes the empty string, undefined, null from the array_Johnny_yellowboy's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/GrootBaby/article/details/126738398