为什么过滤器函数返回空数组?

时间:2020-08-31 08:13:01

标签: javascript

过滤器功能

function filter(array,test) {
    let passed = [];
    for (let element of array){
        if (test(element)) {
            passed.push(element);
        }
    }
    return passed;
}

数组

a = [{name: 'John', sport : 'football'},
    {name: 'Sergio', sport : 'football'},
    {name: 'John', sport : 'basketball'},
    {name: 'Jova', sport : 'football'},
    {name: 'Jon', sport : 'basketball'},
    {name: 'Lemmi', sport : 'football'},
    {name: 'Josh', sport : 'football'},
]

运行代码时

console.log(filter(a, i => i.name['Lemmi']));

我知道了

[]

如何编辑要获取的行

sport: 'football'

输出?

3 个答案:

答案 0 :(得分:5)

i => i.name['Lemmi']返回'Lemmi'中的属性i.name,它不是对象,而是字符串,因此它为所有条目返回undefined

尝试:

console.log(filter(a, i => i.name === 'Lemmi'));

答案 1 :(得分:2)

JavaScript已经具有AVCaptureMetadataOutput方法

.filter()

在您的代码中,您需要使用let a = [{name: 'John', sport : 'football'}, {name: 'Sergio', sport : 'football'}, {name: 'John', sport : 'basketball'}, {name: 'Jova', sport : 'football'}, {name: 'Jon', sport : 'basketball'}, {name: 'Lemmi', sport : 'football'}, {name: 'Josh', sport : 'football'}, ] let result = a.filter(el => el.name === "Lemmi").map(el => ({sport: el.sport})); console.log(result);进行检查,并且仅获取属性el.name === "Lemmi",就可以对其进行映射。

sport

答案 2 :(得分:1)

您的filter函数接收两个参数-输入数组和测试函数。

您的问题有两个不同的问题:

  1. 您将arrow function作为filter函数传递,但是使用的方式不正确。您隐式地通过的是:

    function (i) {
        return i.name['Lemmi'];
    }
    

    而您要做的是:

    function (i) {
        return i.name === 'Lemmi';
    }
    

    因此,您应该通过的是i => i.name === 'Lemmi'

  2. 如果要收集已过滤项目的特定属性,则应传递格式函数:

    function filter(array,test,format) {
          :
          :
        if (test(element)) {
            passed.push(format(element));
       }
    }
    

    然后致电:

    filter(a, i => i.name === 'Lemmi', i => i['sport'])
    
相关问题