代码:
javascript
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
var arr3 = [10, 0, 20, 0, 30, 0, 40, 0, 50];
console.log("原数组为:");
console.log(arr3);
// 开关
let derail = true;
let newarr = [];
let k = 0;
//保留一个0,并排序
arr3.sort(function (a, b) {
return a - b;
});
for (let i = 0; i < arr3.length; i++) {
for (let j = 0; j < newarr.length; j++) {
if (arr3[i] === newarr[j]) {
derail = false;
break;
} else {
derail = true;
}
}
if (derail === true) {
newarr[k] = arr3[i];
k++;
}
}
console.log("去掉重复的0:");
console.log(newarr);
// 不保留0,并排序
arr3.sort(function (a, b) {
return a - b;
});
for (var i = 0; i < arr3.length; i++) {
if (arr3[i] == 0) {
arr3.shift();
i--;
}
}
console.log("去掉全部0:");
console.log(arr3);
</script>
</body>
</html>
效果图: