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

实现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

 

 
 

 

posted on 2015-06-15 14:44  viewcozy  阅读(228)  评论(0编辑  收藏  举报