【问题标题】:How can I list all the properties of Math object?如何列出 Math 对象的所有属性?
【发布时间】:2020-08-31 21:46:16
【问题描述】:

当我这样做时

for (var i in window) console.log(window[i])

我得到一个窗口属性和方法的列表

但是,当我对“数学”对象执行相同操作时,我什么也得不到。

typeof "window" == typeof "Math"

返回 TRUE,所以我看不出我的循环不工作的原因。

奇怪,好像我直接写Math['E']得到的是常量E的值。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    并非所有对象属性都是可迭代的。您只能在 for..in 循环中获得可迭代的属性。

    由于window(恰好是全局对象)的大多数属性都是用户定义的全局变量,因此它们是可枚举的。

    在现代 JavaScript 引擎中,您可以使用 Object.getOwnPropertyNames(obj) 来获取所有属性,包括可枚举的和不可枚举的:

    >>> Object.getOwnPropertyNames(Math)
    ["toSource", "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "exp", "floor", "log", "max", "min", "pow", "random", "round", "sin", "sqrt", "tan", "E", "LOG2E", "LOG10E", "LN2", "LN10", "PI", "SQRT2", "SQRT1_2"]
    

    更多详情请见Is it possible to get the non-enumerable inherited property names of an object?

    【讨论】:

    • 感谢您的解释!但是在这种情况下有没有办法枚举 Math 对象的属性?
    【解决方案2】:
    ["max", "ceil", "SQRT2", "PI", "pow", "log", 
    "LOG2E", "tan", "sqrt", "exp", "random", "min",
    "floor", "atan2", "cos", "atan", "acos", "abs", 
    "round", "asin", "LN2", "LOG10E", "sin",
    "E", "SQRT1_2", "LN10"].forEach( function(key ) {
        if( Math[key] ) {
            console.log( key, Math[key] );
        }
    });
    

    您可以在现代浏览器中使用Object.getOwnPropertyNames( Math ); 获取这些键的列表。以上适用于所有值得注意的浏览器,只要您提供shimmed .forEach

    【讨论】:

    • 谢谢!我不知道 getOwnPropertyNames
    【解决方案3】:
    console.log(Object.getOwnPropertyNames(Math));
    

    【讨论】:

      猜你喜欢
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2010-09-17
      • 2018-02-07
      相关资源
      最近更新 更多