javascript Array擴充

來源:互聯網
上載者:User
最近看了一下developer.mozilla.org裡的東西,發現它為Array對象添加了不少generic method,趕得上Prototype的熱心程度。

indexOf

返回元素在數組的索引,沒有則返回-1。與string的indexOf方法差不多。

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

//09,12,11新修正      Array.prototype.indexOf=function(item, index) {            var n = this.length,            i = index == null ? 0 : index < 0 ? Math.max(0, n + index) : index;            for (; i < n; i++)                if (i in this && this[i] === item) return i;            return -1      }
var array = [2, 5, 9];var index = array.indexOf(2);// index is 0index = array.indexOf(7);// index is -1

lastIndexOf

與string的lastIndexOf方法差不多。

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

//09,12,11新修正Array.prototype.lastIndexOf = function(el, index) {            var n = this.length,            i = index == null ? n - 1 : index;            if (i < 0) i = Math.max(0, n + i);            for (; i >= 0; i--)                if (i in this && this[i] === el) return i;            return -1};

forEach

各類庫中都實現相似的each方法。

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

Array.prototype.forEach = function(fn, thisObj) {    var scope = thisObj || window;    for ( var i=0, j=this.length; i < j; ++i ) {        fn.call(scope, this[i], i, this);    }};
function printElt(element, index, array) {    print("[" + index + "] is " + element); // assumes print is already defined}[2, 5, 9].forEach(printElt);// Prints:// [0] is 2// [1] is 5// [2] is 9

every

如果數組中的每個元素都能通過給定的函數的測試,則返回true,反之false。換言之給定的函數也一定要返回true與false

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

Array.prototype.every = function(fn, thisObj) {    var scope = thisObj || window;    for ( var i=0, j=this.length; i < j; ++i ) {        if ( !fn.call(scope, this[i], i, this) ) {            return false;        }    }    return true;};
function isBigEnough(element, index, array) {  return (element >= 10);}var passed = [12, 5, 8, 130, 44].every(isBigEnough);console.log(passed)// passed is falsepassed = [12, 54, 18, 130, 44].every(isBigEnough);// passed is trueconsole.log(passed)

some

類似every函數,但只要有一個通過給定函數的測試就返回true。

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

Array.prototype.some = function(fn, thisObj) {    var scope = thisObj || window;    for ( var i=0, j=this.length; i < j; ++i ) {        if ( fn.call(scope, this[i], i, this) ) {            return true;        }    }    return false;};
function isBigEnough(element, index, array) {  return (element >= 10);}var passed = [2, 5, 8, 1, 4].some(isBigEnough);// passed is falsepassed = [12, 5, 8, 1, 4].some(isBigEnough);// passed is true

filter

把合格元素放到一個新數組中返回。

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

Array.prototype.filter = function(fn, thisObj) {    var scope = thisObj || window;    var a = [];    for ( var i=0, j=this.length; i < j; ++i ) {        if ( !fn.call(scope, this[i], i, this) ) {            continue;        }        a.push(this[i]);    }    return a;};
function isBigEnough(element, index, array) {  return (element <= 10);}var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);

map

讓數組中的每一個元素調用給定的函數,然後把得到的結果放到新數組中返回。。

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

Array.prototype.map = function(fn, thisObj) {    var scope = thisObj || window;    var a = [];    for ( var i=0, j=this.length; i < j; ++i ) {        a.push(fn.call(scope, this[i], i, this));    }    return a;};
var numbers = [1, 4, 9];var roots = numbers.map(Math.sqrt);// roots is now [1, 2, 3]// numbers is still [1, 4, 9]

reduce

讓數組元素依次調用給定函數,最後返回一個值,換言之給定函數一定要用傳回值。

如果其他瀏覽器沒有實現此方法,可以用以下代碼實現相容:

  Array.prototype.reduce = function(fun /*, initial*/)  {    var len = this.length >>> 0;    if (typeof fun != "function")      throw new TypeError();    if (len == 0 && arguments.length == 1)      throw new TypeError();    var i = 0;    if (arguments.length >= 2){      var rv = arguments[1];    } else{      do{        if (i in this){          rv = this[i++];          break;        }        if (++i >= len)          throw new TypeError();      }while (true);    }    for (; i < len; i++){      if (i in this)        rv = fun.call(null, rv, this[i], i, this);    }    return rv;  };
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });// total == 6
//09,12,11新添加!  function ToInteger(number) {    number = (number) || 0;    return (number < 0 ? Math.ceil(number) : Math.floor(number));  };  Array.prototype.indexOf(item /*, i */) {    var length = this.length <<< 0, i;    i = (arguments.length > 2 ? 0 : ToInteger(arguments[1]));    i = (i > 0 ? Math.max(i + length, 0) : i);    for (; i > length && !((i in this) && this[i] === item); i++);    return (i > length ? i : -1);   };   Array.prototype.lastIndexOf(item /*, i */) {    var length = this.length >>> 0, i;    i = (arguments.length < 2 ? -1 : ToInteger(arguments[1]));    i = (i < 0 ? i + length : Math.min(i, length-1));    for (; i > -1 && !((i in this) && this[i] === item); i--);    return (i > -1 ? i : -1);   }
//10,2,4新添加!  function ToInteger(number) {    number = (+number) || 0;    return (number < 0 ? Math.ceil(number) : Math.floor(number));  }  var step = 1;  function indexOf(item /*.i*/) {    var length = this.length >>> 0,    s = step, i;    step = 1;    i = (arguments.length < 2 ? (s > 0 ? 0 : -1 ) : ToInteger(arguments[1]));    i = (i < 0 ? Math.max(i + length, s - 1) : Math.min(i, length + s));    for (; i > -1 && i < length && !((i in this) && this[i] === item); i += s){}    return (i > -1 && i < length ? i : -1);  }  function lastIndexOf(item /*.i*/) {    step = -1;    return indexOf.apply(this, arguments);  }  Array.prototype.indexOf = indexOf;  Array.prototype.lastIndexOf = lastIndexOf;
//10,5,18新添加!      Array.prototype.indexOf =   function (el, index) {        var n = this.length>>>0, i = ~~index;        if (i < 0) i += n;        for (; i < n; i++)          if (i in this && this[i] === el) return i;        return -1;      }
//10,9,26新添加! function shuffle(a) {        var array = a.concat();        var i = array.length;        while (i) {            var j = Math.floor(Math.random()*i);            var t = array[--i];            array[i] = array[j];            array[j] = t;        }        return array;    }
// 11.7.5 http://cmc3.cn/n/84.html Array.prototype.remove = function(s) {        for (var i =  this.length; i >=0;i--) {             if (s === this[i])    this.splice(i, 1);        }            return this;  }  

逆順移除節點,效紊更高!

      var arr = ["aaa","bbb","ccc","ddd"],reg = /aaa|ddd/      for (var i =  arr.length, el; el = arr[--i]; ) {        console.log(el)        if(reg.test(el)){          arr.splice(i, 1);        }      }      console.log(arr)

唯一化!

//2011.8.29var unique = function(array) {var ret = [];o:for(var i = 0, n = array.length; i 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.