[英]Getting wrong result with Number.isInteger() method, javascript
I've been trying the Number.isInteger() method on chrome console.我一直在 Chrome 控制台上尝试 Number.isInteger() 方法。 and after doing a for loop and checking the result with the
console.log(arr);
并在执行 for 循环并使用
console.log(arr);
检查结果之后console.log(arr);
I'm getting an array with only one value of 1. like this [1];
我得到一个只有一个值为 1 的数组。像这样
[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.每次删除项目时,您都必须返回一步 (
i--
)。
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:您可以使用 typeof 代替:
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. `.splice()' 方法对数组本身进行更改。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.