js数组常用的扩展方法 如取某个元素然后删除

来源:互联网 发布:网络机顶盒桌面软件 编辑:程序博客网 时间:2024/05/21 10:42
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>js_extends.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">--><script type="text/javascript">//用于清空数组Array.prototype.clear = function() {    this.length = 0;}//判断数据项在数组中的位置var oldArrayIndexOf = Array.indexOf;//判断是否原始浏览器是否存在indexOf方法Array.prototype.indexOf = function(obj) {
//要兼容FF,chrome 
    //if(!oldArrayIndexOf) {        for(var i = 0, imax = this.length; i < imax; i++) {            if(this[i] === obj) {                return i;            }        }        return -1;    //} else{   //     return oldArrayIndexOf(obj);   // }}//判断数据项在数组中的位置 lastIndexOfvar oldArraylastIndexOf = Array.lastIndexOf;//判断是否原始浏览器是否存在lastIndexOf方法Array.prototype.lastIndexOf = function(obj) {    
//要兼容FF,chrome
//if(!oldArraylastIndexOf) {        for(var i = this.length; i >= 0; i--) {            if(this[i] === obj) {                return i;            }        }        return -1;    //} else{    //    return oldArraylastIndexOf(obj);    //}}//判断数据项是否在该数组中Array.prototype.contain = function(obj) {    return this.indexOf(obj) !== -1;}//把数据项添加到指定的位置Array.prototype.insertAt = function(index, obj) {    if(index < 0) index = 0;     if(index > this.length) index = this.length;    this.length++;    for(vari = this.length - 1; i > index; i--) {        this[i] = this[i - 1];    }    this[index] = obj;}//返回最有一项数据Array.prototype.last = function() {    return this[this.length - 1];}//移除数组指定索引的值Array.prototype.removeAt = function(index) {    if(index < 0 || index >= this.length) return;    var item = this[index];    for(var i = index, imax = this.length - 2; i < imax; i++) {          this[i] = this[i + 1];     }}//移除数据项的数据Array.prototype.removeObj = function(val) {var index = this.indexOf(val);if (index > -1) {this.splice(index, 1);}};var arr = new Array()arr[0] = "George"arr[1] = "John"arr[2] = "Thomas"arr[3] = "James"arr[4] = "Martin"arr[5] = "Adrew"arr[6] = "Martin"document.write("1.删除之前数据 "+arr.join())arr.removeObj("John")document.write("<br/> ")document.write("删除 arr.removeAt('John');  后的数据 "+arr.join())document.write("<br/> ")var arr = new Array()arr[0] = "George"arr[1] = "John"arr[2] = "Thomas"arr[3] = "James"arr[4] = "Martin"arr[5] = "Adrew"arr[6] = "Martin"document.write("2.Martin的位置: "+arr.lastIndexOf("Martin"))//结果://1.删除之前数据                                                      George,John,Thomas,James,Adrew,Martin//删除 arr.removeAt('John'); 后的数据 George,Thomas,James,Adrew,Martin</script>  </head>    <body>  </body></html>

0 0