Why does for(var i in Math) not iterate through Math.* in Javascript?

前端 未结 4 730
旧巷少年郎
旧巷少年郎 2021-02-14 11:19

For some reason for(var i in Math){console.log(i)} doesn\'t show the expected tan, cos, atan2, E, PI in Javascript.

4条回答
  •  花落未央
    2021-02-14 11:54

    As with most built-in objects in JavaScript, properties and methods of the Math object are defined in the ECMAScript spec (section 15.8.1) as not being enumerable via the (inaccessible to script) DontEnum attribute. In ECMAScript 5, you can mark properties and methods of your own objects as being non-enumerable also:

    var o = {};
    
    Object.defineProperty(o, "p", {
        enumerable: false,
        value: 1
    });
    
    Object.defineProperty(o, "q", {
        enumerable: true,
        value: 2
    });
    
    for (var i in o) {
        console.log(i + "=>" + o[i]);
    }
    // q=>2
    

提交回复
热议问题