![](/img/trans.png)
[英]How could I convert many randomly generated integers into a string of an array in order to perform the forEach() method to check if age >= 18 [DESC]
[英]I need to loop through an array and find the people that are under age 18 . Should i convert it to String (toString) first?
我需要使用循環在數組中找到 18 歲以下的人。 我需要先把它變成一個字符串嗎?
我嘗試創建一個循環通過它的 function,但我不確定如何指向年齡屬性以及返回人名的結果。
var people = [
{ name : 'Matt', age: 19},
{ name : 'George', age: 16},
{ name : 'Ross', age: 12},
{ name : 'Gerard', age: 18},
{ name : 'Leo', age: 15},
{ name : 'Brad', age: 21}
];
控制台中的 output 需要如下所示:
George is 16
Ross is 12
Leo is 15
使用過濾器。 無需制作字符串
var people = [ { name: 'Matt', age: 19}, { name: 'George', age: 16}, { name: 'Ross', age: 12}, { name: 'Gerard', age: 18}, { name: 'Leo', age: 15}, { name: 'Brad', age: 21} ]; console.log(people.filter(function(e){return e.age<18}))
我認為您可以使用 ES6s 過濾器方法來歸檔它。 但是你需要為它填充 JS。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var people = [
{ name : 'Matt', age: 19},
{ name : 'George', age: 16},
{ name : 'Ross', age: 12},
{ name : 'Gerard', age: 18},
{ name : 'Leo', age: 15},
{ name : 'Brad', age: 21}
];
function isJung(p){
return p.age <18 ;
}
var youngPeople = people.filter(isJung);
polyfil 也是 Mozilla 提供的:
if (!Array.prototype.filter){
Array.prototype.filter = function(func, thisArg) {
'use strict';
if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
throw new TypeError();
var len = this.length >>> 0,
res = new Array(len), // preallocate array
t = this, c = 0, i = -1;
var kValue;
if (thisArg === undefined){
while (++i !== len){
// checks to see if the key was set
if (i in this){
kValue = t[i]; // in case t is changed in callback
if (func(t[i], i, t)){
res[c++] = kValue;
}
}
}
}
else{
while (++i !== len){
// checks to see if the key was set
if (i in this){
kValue = t[i];
if (func.call(thisArg, t[i], i, t)){
res[c++] = kValue;
}
}
}
}
res.length = c; // shrink down array to proper size
return res;
};
}
首先filter
然后map
var people = [ { name: 'Matt', age: 19}, { name: 'George', age: 16}, { name: 'Ross', age: 12}, { name: 'Gerard', age: 18}, { name: 'Leo', age: 15}, { name: 'Brad', age: 21} ]; console.log(people.filter(function(e){return e.age<=18}).map(x => x.name+" is " +x.age));
使用過濾器保留好的過濾器和 foreach 顯示。
const people = [
{ name : 'Matt', age: 19},
{ name : 'George', age: 16},
{ name : 'Ross', age: 12},
{ name : 'Gerard', age: 18},
{ name : 'Leo', age: 15},
{ name : 'Brad', age: 21}
];
people.filter(v => v.age < 18).forEach((v)=>{console.log(`${v.name} is ${v.age}`)})
使用 ES6 javascript:
people.forEach((single) => {
if(single.age < 18)
console.log(`${single.name} is ${single.age}`);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.