简体   繁体   中英

Removing empty strings from array in javascript

I need help understanding whats going on in my code. I plan on writing a function that takes in a string and removes all letters. The input will be a combination of letters and numbers. I want this function to return an array of all the numbers found in the string. I have successfully written something(with the help of stackoverflow):

number = "32321FDFDS 44"
arr = number.replace(/[A-Za-z]/g," ").split(" ")



for(var i = arr.length - 1; i >= 0; i--){
     if(arr[i] == "") {
          arr.splice(i, 1);
    }
}

This returns

[ '32321', '44' ]

Which is perfect for now. My question is I don't understand how arr.splice(i,1) is removing empty strings. It doesn't make sense that it is removing the empty strings in arr . Can someone help me understand this?

Test :

if (arr[n] == "") // if item `n` within `arr` array `==` `""` , do stuff

See Array.prototype.splice()

With two items within an array :

 var arr = ["123", ""]; if (arr[0] == "") { arr.splice(0,1); } else { console.log(arr); // ["123", ""]; }; if (arr[1] == "") { arr.splice(1,1); console.log(arr); // ["123"] }; 

Unlike other methods that return a new array, leaving the original variable alone, the .splice method mutates an array, making in-place changes to it.

The statement arr.splice(i, 1); means starting at position i remove one item from the array arr . if(arr[i] == "") means if the item at position i is and empty string, do the stuff inside this block. So when the if statement is true that item is removed from the array.

That said unless you need to support ES3 browsers (which effectively means IE8 or below), instead of looping through the array like that, I would just use the .filter method :

var number = "32321FDFDS 44",
  arr = number.replace(/[A-Za-z]/g," ").split(" ").filter(function (item) {
    return !!item; // all strings except an empty string will coerce to true
  });

console.log(arr);

jsFiddle

If you are just trying to extract an array of numeric strings from a string with no other requirements, an even more succinct way of doing it would be to just split on one or more non-numbers:

var number = "32321FDFDS 44",
  arr = number.split(/\D+/);

// arr is now [ "32321", "44" ]
console.log(arr);

This does it all in one step without having to filter out empty strings at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM