簡體   English   中英

Javascript/jQuery:從數組中刪除所有非數字值

[英]Javascript/jQuery: remove all non-numeric values from array

對於數組: ["5","something","","83","text",""]

如何從數組中刪除所有非數字和空值? 期望的輸出: ["5","83"]

使用array.filter()和一個檢查值是否為數字的回調函數:

var arr2 = arr.filter(function(el) {
    return el.length && el==+el;
//  more comprehensive: return !isNaN(parseFloat(el)) && isFinite(el);
});

array.filter為IE8等舊版瀏覽器提供了array.filter

我需要這樣做,並根據上面的答案跟隨一個兔子蹤跡,我發現這個功能現在已經以$.isNumeric()的形式內置到jQuery本身:

    $('#button').click(function(){
      // create an array out of the input, and optional second array.
      var testArray = $('input[name=numbers]').val().split(",");
      var rejectArray = [];

      // push non numeric numbers into a reject array (optional)
      testArray.forEach(function(val){
        if (!$.isNumeric(val)) rejectArray.push(val)
      });

      // Number() is a native function that takes strings and 
      // converts them into numeric values, or NaN if it fails.
      testArray = testArray.map(Number);

      /*focus on this line:*/
      testArray1 = testArray.filter(function(val){
        // following line will return false if it sees NaN.
        return $.isNumeric(val)
      });
    });

所以,你基本上是.filter() ,你給的函數.filter()$.isNumeric() ,它根據該項是否是數字給出一個真/假值。 有很好的資源可以通過谷歌輕松找到如何使用這些資源。 我的代碼實際上將拒絕代碼推送到另一個數組中,以通知用戶他們上面提供了錯誤的輸入,因此您有兩個功能方向的示例。

這是一個ES6版本,雖然類似於 @Blazemonger 解決方案,但它更簡化了一點:

 let arr = ["5","something","","83","text",""]; const onlyNumbers = arr.filter(v => +v); console.log(onlyNumbers);

在這里,我依賴於將字符串轉換為數字的一元加操作數。 盡管有時它可能會導致一些意外行為(例如true未被過濾),但它與您的數組一起工作得很好,因為它只包含字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM