码迷,mamicode.com
首页 > Web开发 > 详细

JS类库函数收集中....

时间:2015-06-15 16:08:33      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

实现string的substring方法

 

方法一:用charAt取出截取部分

String.prototype.mysubstring=function(beginIndex,endIndex){
    var str=this,
        newArr=[];
    if(!endIndex){
        endIndex=str.length;
    }
    for(var i=beginIndex;i<endIndex;i++){
        newArr.push(str.charAt(i));
    }
    return newArr.join("");
}

//test
"Hello world!".mysubstring(3);//"lo world!"
"Hello world!".mysubstring(3,7);//"lo w"

方法二:把字符串转换成数组然后取出需要部分

String.prototype.mysubstring=function(beginIndex,endIndex){
    var str=this,
        strArr=str.split("");
    if(!endIndex){
        endIndex=str.length;
    }
    return strArr.slice(beginIndex,endIndex).join("");
}

//test
console.log("Hello world!".mysubstring(3));//"lo world!"
console.log("Hello world!".mysubstring(3,7));//"lo w"

方法三:取出头尾部分,然后用replace去掉多余部分,适用于beginIndex较小,字符串长度-endIndex较小的情况

String.prototype.mysubstring=function(beginIndex,endIndex){
    var str=this,
        beginArr=[],
        endArr=[];
    if(!endIndex){
        endIndex=str.length;
    }
    for(var i=0;i<beginIndex;i++){
        beginArr.push(str.charAt(i));
    }
    for(var i=endIndex;i<str.length;i++){
        endArr.push(str.charAt(i));
    }
    return str.replace(beginArr.join(""),"").replace(endArr.join(""),"");
}

//test
console.log("Hello world!".mysubstring(3));//"lo world!"
console.log("Hello world!".mysubstring(3,7));//"lo w"

 

 模拟一个HashTable类,有add、remove、containes、length方法

var HashTable =function(){
    this.container={
        length:0
    };
}

HashTable.prototype={
    add:function(key,value){
        if(key in this.container){
            return false;
        } else {
            this.container[key] = value;
            this.container.length++;
            return true;
        }
    },
    remove:function(key){
        if(key in this.container){
            delete this.container[key];
            this.container.length--;
            return true;
        }
    },
    containes:function(key){
        return (key in this.container);
    },
    length:function(){
        return this.container.length;
    }
}

var test = new HashTable();
test.add(1,123);
test.add(1,123);
test.add(2,123);
test.add(3,123);
test.add(4,123);
test.add(5,123);
console.log(test.containes(3));//true
console.log(test.length());//5
test.remove(3);
console.log(test.containes(3));//false
console.log(test.length());//4

 

 
 

 

JS类库函数收集中....

标签:

原文地址:http://www.cnblogs.com/viewcozy/p/4577149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!