List Object's built-in Properties

前端 未结 5 2047
小蘑菇
小蘑菇 2021-02-06 11:52

Is there a way for me to loop over a Javascript Object\'s built-in properties?

for...in gets me close to where I want to go, but \"A for...in loop does not iterate over

5条回答
  •  遥遥无期
    2021-02-06 12:31

    The answer is no. You can't enumerate properties that aren't enumerable. There are however at least two ways around this.

    The first is to generate all possible combination of characters to use as test property names (think: a, b, c, ... aa, ab, ac, ad, ... ). Given that the standards community is famous for coming up with really long method names (getElementsByTagNames, propertyIsEnumerable) this method will require some patience. :-)

    Another approach is to test for known native properties from some predefined list.

    For example: For an array you would test for all known native properties of Function.prototype:

    prototype caller constructor length name apply call toSource toString valueOf toLocaleString
    

    ...and things inherited from Object.prototype:

    __defineGetter__ __defineSetter__ hasOwnProperty isPrototypeOf __lookupGetter__
    __lookupSetter__ __noSuchMethod__ propertyIsEnumerable unwatch watch
    

    ...and things inherited from Array:

    index input pop push reverse shift sort splice unshift concat join slice indexOf lastIndexOf 
    filter forEach every map some reduce reduceRight
    

    ..and finally, and optionally, every enumerable property of the object you are testing:

    for (var property in myArrayObject) myPossibleProperties.push( property );
    

    You'll then be able to test every one of those to see if they are present on the object instance.

    This won't reveal unknown non-enumerable members (undocumented, or set by other scripts), but will allow you to list what native properties are available.

    I found the information on native Array properties on Mozilla Developer Center and MSDN.

提交回复
热议问题