最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why filter return [object Object]? - Stack Overflow

programmeradmin3浏览0评论
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].

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].

Share Improve this question edited Apr 18, 2016 at 22:24 Mike Cluck 32.5k13 gold badges83 silver badges94 bronze badges asked Apr 18, 2016 at 22:19 EhsanEhsan 13k3 gold badges26 silver badges46 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

The filter needs to return true to keep the element or false otherwise.

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

You're seeing [object Object], [object Object] because you're trying to display an array of objects as a string. That's happening because you seem to think that filter creates a string based on it's return value. That's not how filter works. filter takes a function which returns true or false and creates a new array with only the results that returned 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.

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

Finally, to convert an array into a single string, you can use join.

document.getElementById("x").innerHTML = adultNames.join('and');
发布评论

评论列表(0)

  1. 暂无评论