4题:在String()构造函数不存在的情况下自定义一个MyString()的构造器函数。记住,由于String()不存在,因此您在写构造器函数时不能使用任何属于内建String对象的方法和属性。并且要让您所创建的对象通过以下测试:var s = new MyString("hello"); s.length; //5 s[0]; //"h" s.toString(); //"hello" s.valueOf(); //"hello" s.charAt(1); //"e" s.charAt("2"); //"l" s.charAt("e"); //"h" s.concat(" world!"); //"hello world!" s.slice(1,3); //"el" s.slice(0,-1); //"hell" s.split("e"); //["h","llo"] s.split("l"); //["he","","o"]
测试都通过了。代码如下:
function MyString(val){
var list = [],i;
for(i in val){
list[i] = val[i];
}
this.length = list.length;
this.toString=function(){
return list.join('');
};
this.valueOf=function(){
return list.join('');
};
this.charAt=function(index){
return list[isNaN(parseInt(index))?0:(parseInt(index))];
};
this.concat=function(str){
for(var i in str){
list.push(str[i]);
}
return list.join('');
};
this.slice=function(n1,n2){
var s1 = [];
if(n2>n1){
for(var i=n1;i 来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1451/viewspace-2799551/ ,如需转载,请注明出处,否则将追究法律责任。