Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - How can I list all the properties of Math object?

When I do

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

I get a list of window properties and methods

Howver when I do the same for "Math" object, I get nothing.

typeof "window" == typeof "Math"

returns TRUE, so I do not see a reason why my loop is not working.

It's strange as if I write directly Math['E'] I get the value of constant E.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not all object properties are iterable. You'll only get iterable properties in a for..in loop.

Since most properties of window (which happens to be the global object) are user-defined global variables, they are enumerable.

In modern JavaScript engines you can use Object.getOwnPropertyNames(obj) to get all properties, both enumerable and non-enumberable:

>>> 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"]

See Is it possible to get the non-enumerable inherited property names of an object? for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...