使用javascript从数组中筛选出数字索引

Filtering out numeric indexes from an array with javascript

本文关键字:数字 索引 筛选 javascript 数组 使用      更新时间:2023-09-26

这是我为从数组中筛选出数值而编写的代码,但它返回的是完整的数组。我无法找出代码中的问题。请帮帮我,我被卡住了。。。

<!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>

typeof检查中的打字:

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

JavaScript数组有一个内置的过滤方法:

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

至于您的原始代码,请注意typeof是一个运算符,而不是一个函数,因此

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

相当于

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

其评估为

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

这将永远是真的,这就是为什么你最终得到的整个内容没有任何过滤。

还要注意的是,+=运算符并没有重载数组,您最终会得到剩余值的字符串串接:

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

必须使用push方法:

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