HTML
<p id="demo"></p>
JS
const kids = [
{ name: 'fluffy', age: 5 },
{ name: 'archimedes', age: 9 },
{ name: 'meowth', age: 3 },
{ name: 'gertrude', age: 4 },
{ name: 'penelope', age: 7}
];
document.getElementById("demo").innerHTML = xxx;
我想在p
内打印姓名和年龄,以显示5岁及以上儿童的姓名
我还做了fiddle
答案 0 :(得分:3)
您可以通过Array.filter()
根据条件过滤数组。然后你可以通过Array.map()
将数组元素映射到它们的字符串表示中:
const kids = [
{ name: 'fluffy', age: 5 },
{ name: 'archimedes', age: 9 },
{ name: 'meowth', age: 3 },
{ name: 'gertrude', age: 4 },
{ name: 'penelope', age: 7}
];
// Filter kids array by given condition:
let selection = kids.filter(kid => kid.age >= 5);
// Map selected kids to strings:
let strings = selection.map(({name, age}) => `${name}, ${age} years old`);
// Concatenate strings for output:
document.getElementById('demo').textContent = strings.join('; ');
<p id="demo"></p>
答案 1 :(得分:1)
您可以先过滤然后迭代过滤后的数组。因此,请使用rm /Users/<username>/.credentials/<authorization.json>
和Array#filter
Array#forEach
const kids = [{
name: 'fluffy',
age: 5
},
{
name: 'archimedes',
age: 9
},
{
name: 'meowth',
age: 3
},
{
name: 'gertrude',
age: 4
},
{
name: 'penelope',
age: 7
}
];
var filteredKids = kids.filter(x => x.age>=5);
var ans="";
filteredKids.forEach((v,i) => ans+= 'name:'+v.name+', age:'+v.age+' ');
//console.log(ans);
document.getElementById("demo").innerHTML = ans;