【问题标题】:Why doesn't Object.getOwnPropertyNames() list all properties and methods?为什么 Object.getOwnPropertyNames() 不列出所有属性和方法?
【发布时间】:2018-06-15 07:00:48
【问题描述】:

我正在尝试从恰好是字符串的对象中提取所有属性和方法:var str = "Hello World!"

如果我使用命令Object.getOwnPropertyNames(str),我会得到一个属性和方法列表:["0", "1", "2", "3", "length"]。但是我知道还有其他方法,例如.toUpperCase(),它们属于字符串对象,但没有列出。

我的问题:为什么没有列出方法.toUpperCase()?我该怎么做才能与许多其他人一起列出它 (.indexOf()...)?

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Display properties and methods from objects</title>
</head>
<body>
    <script type="text/javascript">
    var str= 'Hello World!'
    var listPropertiesMethods = Object.getOwnPropertyNames(str)
    console.log(listPropertiesMethods);
    </script>
</body>
</html>

【问题讨论】:

  • @JonasW。我得到空数组....
  • 哦,对,不适用于 Object.keys,但可以使用 getOwnPropertyNames
  • @JonasW。好的,但 getOwnPropertyName 是我用过的,并没有像我问的那样返回所有方法......我还需要打印出其他方法,例如 toUpperCase()
  • @JonasW。是的,当然:)

标签: javascript object methods properties


【解决方案1】:

因为您列出的属性 (indexOf, ...) 不是字符串对象本身的一部分,而是其原型的一部分:

Object.getOwnPropertyNames(
 Object.getPrototypeOf("str")
)

【讨论】:

    【解决方案2】:

    Object.getOwnPropertyNames(obj) 方法仅返回 obj 的属性(如长度)。您可以使用Object.getPrototypeOf(obj) 获取更完整的方法/属性列表。

    例如:

    Object.getOwnPropertyNames("Test")

    (5) ["0", "1", "2", "3", "length"]
    

    Object.getPrototypeOf("Test")

    String {"", formatUnicorn: ƒ, truncate: ƒ, splitOnLast: ƒ, contains: ƒ, length: 0, …}
    

    【讨论】:

      【解决方案3】:

      您只需查看对象的原型,就可以得到您想要的:

      console.log(str.__proto__);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-12
        • 1970-01-01
        • 2011-07-09
        • 1970-01-01
        相关资源
        最近更新 更多