简体   繁体   English

使用JavaScript从数组中过滤出数字索引

[英]Filtering out numeric indexes from an array with javascript

This is the code i have written to filter out Numeric values from an array, but it is returning the complete array. 这是我编写的用于从数组中滤除数值的代码,但它返回的是完整的数组。 I am not able to find out the problem in my code. 我无法在我的代码中找到问题。 Please help me i am stuck... 请帮助我,我被困住了...

<!doctype html>
<html lang="en">
    <head>
  <meta charset="utf-8">
  <title>html demo</title>
</head>
<body>
<script>
    arr = ["apple", 5, "Mango", 6];
    function filterNumeric(arrayName){
        var i = 0;
        var numericArray=[];
        for (i; i <arrayName.length;i++){
            if (typeof(arrayName[i] === 'number')) {
                numericArray+=arrayName[i];
            }
        }
        return numericArray;
    }

    var filter = filterNumeric(arr);
    alert(filter);
</script>

</body>
</html>

Typo in the typeof check: typeof检查中输入:

if (typeof(arrayName[i]) === 'number') {
//                    ^^^ close the parentheses here
//                                 ^^^ not there

JavaScript arrays have a built-in filtering method : JavaScript数组具有内置的过滤方法

var arr = ["apple", 5, "Mango", 6];
var filtered = arr.filter(function(item) { return (typeof item === "number")});
console.log(filtered); // Array [5,6]

As for your original code, beware that typeof is an operator, not a function, so 至于您的原始代码,请注意typeof是运算符,而不是函数,因此

if (typeof(foo === "whatever")) {
    // ...
}

is equivalent to 相当于

if (typeof some_boolean_value) {
    // ...
}

which evaluates to 评估为

if ("boolean") {
    // ...
}

which will always be true, this is why you ended up with the whole content with no filtering whatsoever. 这将永远是正确的,这就是为什么您最终没有过滤就得到全部内容的原因。

Also note that the += operator is not overloaded for arrays, you will end up with a string concatenation of the remaining values: 还要注意,数组的+=运算符未重载,您将得到其余值的字符串连接:

var foo = [];
var bar = [1,2,3,4];
foo += bar[2];
console.log(foo); // "3"
console.log(typeof foo); // "string"

you must use the push method instead: 您必须改用push方法:

var foo = [];
var bar = [1,2,3,4];
foo.push(bar[2]);
console.log(foo); // Array [3]
console.log(typeof foo); // "object"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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