首页 > 解决方案 > JavaScript 数组过滤器返回未定义

问题描述

我试图了解在使用不同的语法/方法编写函数时适用于数组映射的规则。

    var MyArray = ["Item1", "Item2", "Item3", "Item4"]

function removeEveryOther(array){
    array.filter(function(value, index) {
        return index % 2 === 0;
    })
}

var Filtered = MyArray.removeEveryOther;
console.log(Filtered);

我想使用过滤器从数组中删除所有其他元素。由于某种原因,上述返回未定义,为什么?

标签: javascriptarrays

解决方案


首先,您需要在此处返回.filter()方法结果,例如:

function removeEveryOther(array) {
  return array.filter(function(value, index) {
    return index % 2 === 0;
  })
}

否则,您正在做的主要是返回 undefined ,例如:

function removeEveryOther(array) {}
console.log( removeEveryOther([]) )  //=> returns "undefined"

然后,您需要removeEveryOther()通过传递数组来正确调用该函数,例如:

var Filtered = removeEveryOther(MyArray);
console.log(Filtered);

演示(ES5):

var MyArray = ["Item1", "Item2", "Item3", "Item4"]

function removeEveryOther(array){
    return array.filter(function(value, index) {
        return index % 2 === 0;
    })
}

var Filtered = removeEveryOther(MyArray);
console.log(Filtered);

演示(ES6):

var MyArray = ["Item1", "Item2", "Item3", "Item4"]
function removeEveryOther(array){
  return array.filter((value, index) => index % 2 === 0);
}

var Filtered = removeEveryOther(MyArray);
console.log(Filtered);


推荐阅读