如何打印javascript String对象的属性和方法.
以下代码段不会打印任何内容.
for (x in String) {
document.write(x);
}
Run Code Online (Sandbox Code Playgroud)
属性String都是不可枚举的,这就是你的循环没有显示它们的原因.您可以使用以下Object.getOwnPropertyNames函数在ES5环境中查看自己的属性:
Object.getOwnPropertyNames(String);
// ["length", "name", "arguments", "caller", "prototype", "fromCharCode"]
Run Code Online (Sandbox Code Playgroud)
您可以使用以下Object.getOwnPropertyDescriptor函数验证它们是不可枚举的:
Object.getOwnPropertyDescriptor(String, "fromCharCode");
// Object {value: function, writable: true, enumerable: false, configurable: true}
Run Code Online (Sandbox Code Playgroud)
如果要查看String实例方法,则需要查看String.prototype.请注意,这些属性也是不可枚举的:
Object.getOwnPropertyNames(String.prototype);
// ["length", "constructor", "valueOf", "toString", "charAt"...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
669 次 |
| 最近记录: |