Javascript - 尝试使用属性过滤数组

时间:2017-10-31 18:31:46

标签: javascript html filter

以下是我遇到的一些示例代码。我认为这与阵列的属性有什么关系?我希望使用联盟属性过滤数组。

<script>
var teams = [
{name: "newcastle", league: "Premiership"},
{name: "Hull", league: "League 1"},
{name: "Sunderland", league: "League 1"},
{name: "Arsenal", league: "Premiership"}];

var filterLeague = teams.filter(function (teams) {
 return (teams.league === "Premiership");
});

document.getElementById("output").innerHTML = filterLeague;

</script>

3 个答案:

答案 0 :(得分:4)

过滤结果是对象数组。你需要将它转换为某种字符串才能显示在DOM元素中

<div id='output'></div>
<script>
var teams = [
{name: "newcastle", league: "Premiership"},
{name: "Hull", league: "League 1"},
{name: "Sunderland", league: "League 1"},
{name: "Arsenal", league: "Premiership"}];

var filterLeague = teams.filter(function (teams) {
 return (teams.league === "Premiership");
});

document.getElementById("output").innerHTML = JSON.stringify(filterLeague);

</script>

答案 1 :(得分:1)

改变这个:

document.getElementById("output").innerHTML = filterLeague

到此:

document.getElementById("output").innerHTML = JSON.stringify(filterLeague);

答案 2 :(得分:0)

你的过滤器工作正常,但它返回的是一个数组,所以添加它innerHTML不会很好。

根据您的目的,您可以通过几种方法创建输出。您可以像其他答案建议的那样对您的数组进行字符串化或者,您可以使用.map()迭代每个结果,将其作为新的html元素添加。

var teams = [
{name: "newcastle", league: "Premiership"},
{name: "Hull", league: "League 1"},
{name: "Sunderland", league: "League 1"},
{name: "Arsenal", league: "Premiership"}];

teams
.filter(function (teams) {
 return (teams.league === "Premiership");
})
.map(function(team) {
  var ul = document.getElementById('map-output');
  var li = document.createElement('li');
  li.innerText = team.name;
  ul.appendChild(li);
});
<ul id="map-output"></ul>