複製代碼 代碼如下:
<html>
<head>
<title> Extend JavaScript Array Method </title>
<script language="javascript">
<!--
Array.prototype.indexOf=function(substr,start){
var ta,rt,d='\0';
if(start!=null){ta=this.slice(start);rt=start;}else{ta=this;rt=0;}
var str=d+ta.join(d)+d,t=str.indexOf(d+substr+d);
if(t==-1)return -1;rt+=str.slice(0,t).replace(/[^\0]/g,'').length;
return rt;
}
Array.prototype.lastIndexOf=function(substr,start){
var ta,rt,d='\0';
if(start!=null){ta=this.slice(start);rt=start;}else{ta=this;rt=0;}
ta=ta.reverse();var str=d+ta.join(d)+d,t=str.indexOf(d+substr+d);
if(t==-1)return -1;rt+=str.slice(t).replace(/[^\0]/g,'').length-2;
return rt;
}
Array.prototype.replace=function(reg,rpby){
var ta=this.slice(0),d='\0';
var str=ta.join(d);str=str.replace(reg,rpby);
return str.split(d);
}
Array.prototype.search=function(reg){
var ta=this.slice(0),d='\0',str=d+ta.join(d)+d,regstr=reg.toString();
reg=new RegExp(regstr.replace(/\/((.|\n)+)\/.*/g,'\\0$1\\0'),regstr.slice(regstr.lastIndexOf('/')+1));
t=str.search(reg);if(t==-1)return -1;return str.slice(0,t).replace(/[^\0]/g,'').length;
}
window.onload=function(){
var a=new Array('aa1321321','b4323424b','cc345345','dd4654','dd4654','b4323424b');
document.getElementById('t1').value=a.toString();
//document.getElementById('t2').value=a.indexOf('cc345345');
//document.getElementById('t3').value=a.lastIndexOf('dd4654');
document.getElementById('t4').value=a.replace('b4323424b','*');//把第一個b4323424b替換成*
document.getElementById('t5').value=a.search(/dd4654/);//未找到返回-1
};
//-->
</script>
<style type="text/css">
<!--
input{width:600px}
//-->
</style>
</head>
<body>
<table>
<tr><td>數組a:</td><td><input id="t1" type="text" /></td></tr>
<tr><td>a.indexOf('cc345345'):</td><td><input id="t2" type="text" /></td></tr>
<tr><td>a.lastIndexOf('dd4654'):</td><td><input id="t3" type="text" /></td></tr>
<tr><td>a.replace(/\d/g,'*'):</td><td><input id="t4" type="text" /></td></tr>
<tr><td>a.search(/dd4654/):</td><td><input id="t5" type="text" /></td></tr>
</table>
</body>
</html>