简体   繁体   中英

Getting wrong result with Number.isInteger() method, javascript

I've been trying the Number.isInteger() method on chrome console. and after doing a for loop and checking the result with the console.log(arr); I'm getting an array with only one value of 1. like this [1];

 var arr = [1,2,3,'some','string'];

for (var i = 0; i < arr.length; i++) {
    if (Number.isInteger(arr[i])) {
        arr.splice(arr.indexOf(arr[i], 1));
    }
}

Any one have an idea, if I'm doing it wrong or something. thanks for help.

You have a major problem, you are continually removing items from the array while looping through it. You have to go back one step ( i-- ) every time an item is removed.

 var arr = [1,2,3,'some','string']; for (var i = 0; i < arr.length; i++) { if (!isNaN(arr[i])) { // isNaN return true if it's not a valid number, so we have to inverse the test arr.splice(i, 1); // if it's a valid number remove the element at the index i (no need to search for the index using indexOf, we already have it its i) i--; // if we remove an element, we have to go back one step (or we will leave one item behind every time we remove another) } } console.log(arr);

You could use typeof instead:

var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
  if (typeof arr[i] == 'number') {
    arr.splice(arr.indexOf(arr[i], 1));
  }
}

The `.splice()' method makes changes to the array itself.

So for each iteration of the array, you are changing it fundamentally.

If you want the array to include only integers:

    var arr = [1,2,3,'some','string'];

    var newArray = [];

    arr.forEach(function(element) {
        if (Number.isInteger(element)){
            newArray.push(element);
        }
    });

    console.log(newArray);

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