一,假设 js 中不存在 Math 对象, 然后自己定义一个 MyMath 对象. 要实现的要求是给自定义的 MyMath 中添加一个方法, 可以返回一个指定范围的随机整数 [min, max] MyMath.rand(min,max) 随机返回 min 到 max 区间的一个数, 闭区间.
代码实现:
javascript 代码效果预览
二,在 String() 构造器不存在的情况下自定义: MyString() 的构造器函数.假设 String() 不存在,所以在写该构造函数时不能使用任何属于内建 String 对象的方法和属性.并且要让我们所创建的对象能通过以下测试:
function MyMath() {}
MyMath.rand=function (min,max) {
if((typeof min!== "number") || (typeof max!== "number") || (min>=max)){
return false;
}else {
var d = new Date();
var randNum=d.getMilliseconds()/1001;// 利用时间毫秒的方式自动生成 0 到 1 之间的数
return parseInt(randNum*(max - min + 1) + min);// 然后在该范围内转换成 0 到 1 之间的整数
}
}
console.log(MyMath.rand(0, 10));
代码实现:
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"]
javascript 代码效果预览
function MyString(s) {
this.str=s.toString();// 先将输入的参数自动转换成字符串放到它的 str 里面作为内容
this.length=this.str.length;// 获取字符串长度
for (var i=0;i<this.length;i++){
this[i]=this.str[i];// 将 str 里面的内容自动的转换成 MyString 的内容
}
// 构造 toString 方法 (都要让他转换成字符串)
this.toString=function (){
return this.str;
};
// 构造 valueOf 方法 (都要让他转换成字符串)
this.valueOf=function (){
return this.toString();
};
// 构造 charAt 方法 (通过给出下标找字符的功能), 使输入下标 index 返回指定位置的字符串
this.charAt=function(index){
index=parseInt(index);// 使下标转换成整数
index=isNaN(index)?0:index;// 让下标必须是数字
return this[index];// 返回 MyString 输入的那个字符串所指定的下标的字符
};
// 构造 concat 方法
this.concat=function(concatStr){
return this.str+concatStr;
};
// 构造 slice 方法 (截取字符串的功能), 注意截取的字符串不到 endIndex 下标
this.slice=function(startIndex,endIndex){
while(startIndex<0){
startIndex=startIndex+this.length;// 如果是负数,让它从数组尾部的位置开始算起
}
while(endIndex<0){
endIndex=endIndex+this.length;// 如果是负数,让它从数组尾部的元素开始算起
}
if(endIndex<=startIndex){
return "";// 如果是前面下标大于后面下标, 就让它不输出字符串, 以空白代替
}
var strOfSlice="";
for(var i=startIndex;i<endIndex;i++){
strOfSlice+=this[i];// 将截取的字符集装进这个这个方法的容器里
}
return strOfSlice;
};
// 构造 split 方法 (切割字符串成数组的功能)
this.split=function(s){
var arrOfSplit=[];// 创建空数组用来存储切割后的字符集
var tempStr="";
for(var i=0;i<this.length;i++){
if(this[i]===s){// 如果要用来切割的那个字符在该字符串里,
// 先把它前一个字符放进来, 后面默认使用 "" 占位, 实现跳过该字符的效果
arrOfSplit.push(tempStr);
tempStr="";
}else{
tempStr+=this[i];// 如果要用来切割的那个字符是其他字符, 就每次加一个字符
}
}
arrOfSplit.push(tempStr);// 添加进来的字符就是切割完了的数组
return arrOfSplit;
};
}
var s = new MyString('hello');
console.log(s.length); // 5
console.log(s[0]); // "h"
console.log(s.toString()); //"hello"
console.log(s.valueOf()); //"hello"
console.log(s.charAt(1)); //"e"
console.log(s.charAt('2')); //"l"
console.log(s.charAt('e')); //"h"
console.log(s.concat('world!')); //"hello world!"
console.log(s.slice(1, 3)); //"el"
console.log(s.slice(0, -1)); //"hell"
console.log(s.split('e')); //"h", "llo"]
console.log(s.split('l')); //["he", "","o"]
来源: http://www.qdfuns.com/notes/48922/ae3a27b05aee31dc85f7ced2ac086dcb.html