JS类库函数收集中....
2024-09-22 00:07:57
实现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
最新文章
- OpenCascade MeshVS Usage
- First,FirstOrDefault,Single,SingleOrDefault的区别
- 【代码笔记】iOS-钢琴小游戏
- 解决git pull 命令失效,不能从远程服务器上拉取代码问题
- 問題排查:System.BadImageFormatException: 未能加载文件或程序集“System.ServiceModel
- IE下必须点击一下页面空白的地方才可以激活onchange事件
- 【Linq to Object】使用LINQ实现左链接加GROUP BY查询
- shell 检测ip的合法性与检测网络掩码的合法性
- jmeter接口测试之登录测试
- 【转】最新基于adt-bundle-windows-x86的android开发环境搭建
- 功能点分析法FPA笔记
- 获取css的属性值
- Elon Musk:同一时候颠覆几个行业的科技狂人
- git 删除远程主分支及其它操作
- ubuntu 中 ThinkPHP 上传文件无法得到文件名
- MySQL、PHP入门
- Algorithm -->; 阶乘和因子
- operation=
- [C++]四分树(Quadtrees)
- MogileFS-2.44 安装与配置
热门文章
- CF Two Substrings
- 启动 Eclipse 弹出“Failed to load the JNI shared library jvm.dll”错误的解决方法!&;&;在eclipse.ini中为eclipse指定jdk启动
- 设置UITableView背景透明/监听cell左边的删除按钮的点击事件
- AngularJS 学习笔记(1)
- Ubuntu系统下载工具的推荐
- VHDL MOD和REM(转)
- Java学习之Java的单例模式
- 杭电ACM2097--Sky数
- Arduino CNC Shiled 和 DRV8825驱动板的注意事项
- 《DNS服务缓存的建立》RHEL6