移除数组中的空字符串元素
使用 filter 方法对数组进行拷贝,删除空字符串元素,保留其他元素(第 22 ~ 24 行):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Remove empty string from array</title>
</head>
<body>
<script type="text/javascript">
window.onload = (event) => {
// console.log(event);
main();
}
function main() {
const str = "TP2 27.3000 2.3000 180 m TP-2D6";
// 将字符串分割成字符串,并没有从数组中删除空字符串元素
const split1 = str.split(" ");
console.log(`The length of split1: ${split1.length}`, split1);
// 使用 filter 方法对数组进行拷贝,删除空字符串元素,保留其他元素
const split2 = str.split(" ").filter((element) => {
return element !== ""; // 根据该条件判断数组元素是否为空字符串
});
console.log(`The length of split2: ${split2.length}`, split2);
}
</script>
</body>
</html>
控制台输出: