從 JavaScript 中的陣列中移除“0”、“undefined”和空值


要刪除“0”、“undefined”以及空值,你需要使用 splice() 概念。假設以下內容是我們的陣列 −

var allValues = [10, false,100,150 ,'', undefined, 450,null]

以下是使用 for 迴圈和 splice() 的完整程式碼 −

示例

var allValues = [10, false,100,150 ,'', undefined, 450,null]
console.log("Actual Array=");
console.log(allValues);
for (var index = 0; index < allValues.length; index++) {
   if (!allValues[index]) {
      allValues.splice(index, 1);
      index--;
   }
}
console.log("After removing false,undefined,null or ''..etc=");
console.log(allValues);

要執行上述程式,你需要使用以下命令 −

node fileName.js.

此處,我的檔名是 demo88.js。

輸出

這將產生以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo88.js
Actual Array=
[ 10, false, 100, 150, '', undefined, 450, null ]
After removing false,undefined,null or ''..etc=
[ 10, 100, 150, 450 ]

更新於: 07-Sep-2020

175 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告