- 反射
- 枚举
var persons = [{
name: "Peter",
age: 20
},{
name: "Fox",
ages: "21"},
,{
name: "Fox",
age: "21"}
]
一个被用作过滤器的对象。
var types={
name: "string",
age:"number"
}
每个 persons 对象都会被检查是否具有 name 和 age 属性。Object.keys 返回对象属性的数组。
在其他语言中,这比这个一行代码要复杂得多。
console.log(persons.filter(function(person){
return Object.keys(person).filter(function(property){
return types[property] && typeof person[property] === types[property];
}).length === requiredProps.length;
}));
此外,所需类型 - 字符串和数字也会进行检查。
但为什么呢?有不同的情况,例如在 Web 应用程序内,您需要检查用户是否指定了某些必需的输入。而且在编程中,您经常需要对数组中的对象进行操作。因此,数组函数 filter、reduce 和 map 经常用于将某些输入转换为某些输出。无论是用于函数还是一些服务器 API。
敬礼