JS數組追加數組採用push.apply的坑

來源:互聯網
上載者:User

JS數組追加數組沒有現成的函數,這麼多年我已經習慣了a.push.apply(a, b);這種自以為很酷的,不需要寫for迴圈的寫法,一直也沒遇到什麼問題,直到今天我要append的b是個很大的數組時才遇到了坑。  a = new Array();     b = new Array(125624);                     a.push.apply(a, b);以上的代碼在mac的chrome下拋出了如下的異常  Uncaught RangeError: Maximum call stack size exceeded如果把數組改為b = new Array(125623);小一個元素居然就好了,測試了一下其他瀏覽器也都有大數組才出錯的問題,但不同瀏覽器臨界值還各異。 搜尋了http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/17368101#17368101 發現也有人遇到這樣的坑:  Array.prototype.extend = function (other_array) {    /* you should include a test to check whether other_array really is an array */    other_array.forEach(function(v) {this.push(v)}, this);    }給出的建議是老老實實用forEach,不僅可以避免大數組的異常問題,並且從效能角度考慮forEach也是最快的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.