打印javascript字符串对象属性和方法

print the javascript string object properties and methods

本文关键字:方法 属性 对象 javascript 字符串 打印      更新时间:2023-09-26

如何打印javascript字符串对象的属性和方法

下面的代码段不打印任何东西。

for (x in String) {
   document.write(x);   
}

String的属性都是不可枚举的,这就是为什么你的循环没有显示它们。您可以在ES5环境中使用Object.getOwnPropertyNames函数查看自己的属性:

Object.getOwnPropertyNames(String);
// ["length", "name", "arguments", "caller", "prototype", "fromCharCode"]

你可以用Object.getOwnPropertyDescriptor函数验证它们是不可枚举的:

Object.getOwnPropertyDescriptor(String, "fromCharCode");
// Object {value: function, writable: true, enumerable: false, configurable: true}

如果您想查看String实例方法,则需要查看String.prototype。注意,这些属性也是不可枚举的:

Object.getOwnPropertyNames(String.prototype);
// ["length", "constructor", "valueOf", "toString", "charAt"...

首先它必须声明为Object,(可以使用'new'关键字)

s1 = "2 + 2";               
s2 = new String("2 + 2");   
console.log(eval(s1));      
console.log(eval(s2));      

console.log(eval(s2.valueOf()));

尝试在Chrome的开发人员工具或Firefox的Firebug中使用控制台。

and try this

    for (x in new String()) {
       console.log(x);   
    }

这应该可以完成工作:

 var StringProp=Object.getOwnPropertyNames(String);
 document.write(StringProp); 
 -->>  ["length", "name", "arguments", "caller", "prototype", "fromCharCode"]

但你可能更感兴趣的是:

 var StringProtProp=Object.getOwnPropertyNames(String.prototype);
 document.write(StringProtProp); 
-->> ["length", "constructor", "valueOf", "toString", "charAt", "charCodeAt", "concat", 
"indexOf", "lastIndexOf", "localeCompare", "match", "replace", "search", "slice", "split", 
"substring", "substr", "toLowerCase", "toLocaleLowerCase", "toUpperCase", "toLocaleUpperCase",
 "trim", "trimLeft", "trimRight", "link", "anchor", "fontcolor", "fontsize", "big", "blink", 
"bold", "fixed", "italics", "small", "strike", "sub", "sup"]