对象反射和枚举 - JavaScript

Object Reflection & Enumeration - JavaScript

我目前正在阅读 Douglas Rockford 的 "JavaScript The Good Parts",我遇到了以下两个主题:

  1. 反思
  2. 枚举

据书:

It is easy to inspect an object to determine what properties it has by attempting to retrieve the properties and examining the values obtained.The typeof operator can be very helpful in determining the type of a property.

虽然我听懂了,但是我们可以使用对象反射来基本查看它包含的所有属性和值。比如从产品背面读取成分,看看它到底是由什么制成的。

我的问题是为什么以及如何?为什么需要使用对象反射,在什么场景下使用它有什么好处以及枚举如何连接?反射和枚举之间的link是什么?

提前致谢。

在 JS 中,对象通常以非常动态的方式创建。看看下面的片段。

一组动态创建的对象。

    var persons = [{
      name: "Peter",
      age: 20
    },{
      name: "Fox",
      ages: "21"},
      ,{
      name: "Fox",
      age: "21"}
    ]

用作过滤器的对象。

var types={
    name: "string",
    age:"number"
}

检查 persons 中的每个对象是否具有 属性 姓名和年龄。 Object.keys returns 对象属性的数组。

在其他语言中,这比这个衬里要复杂得多。

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。

此致