简体   繁体   English

为什么过滤器返回[object Object]?

[英]why filter return [object Object]?

var persons = [
    {name : "jak" , age:20},
    {name : "hasan" , age: 15},
    {name : "reza" , age:18}
];

function adult(el,index,arr){
    if (el.age >= 18)
        return el.name;
    }

    document.getElementById("x").innerHTML = persons.filter(adult);
}

I expected jak and reza , but i see [object object] [object object]. 我期望jak和reza,但是我看到[object object] [object object]。

The filter needs to return true to keep the element or false otherwise. 过滤器需要返回true以保留元素,否则返回false。

See below: 见下文:

 var persons = [{ name: "jak", age: 20 }, { name: "hasan", age: 15 }, { name: "reza", age: 18 }]; function adult(el, index, arr) { if (el.age >= 18) return true; } document.getElementById("x").innerHTML = persons.filter(adult).map(function(person) { return person.name; }); 
 <div id='x'></div> 

Reference: MDN 参考: MDN

You're seeing [object Object], [object Object] because you're trying to display an array of objects as a string. 您正在看到[object Object], [object Object]因为您试图将对象数组显示为字符串。 That's happening because you seem to think that filter creates a string based on it's return value. 发生这种情况是因为您似乎认为filter会根据返回值创建一个字符串。 That's not how filter works. 那不是filter工作原理。 filter takes a function which returns true or false and creates a new array with only the results that returned true . filter接受一个返回truefalse的函数,并仅使用返回true的结果创建一个新数组。

var adults = persons.filter(function(person) {
  return person.age >= 18;
});

If you want to map certain elements in an array to something else you can use map . 如果要将数组中的某些元素映射到其他对象,则可以使用map

var adultNames = adults.map(function(person) {
  return person.name;
});

Finally, to convert an array into a single string, you can use join . 最后,要将数组转换为单个字符串,可以使用join

document.getElementById("x").innerHTML = adultNames.join('and');

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

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