JS數(shù)組方法push()、pop()用法實例分析
本文實例講述了JS數(shù)組方法push()、pop()用法。分享給大家供大家參考,具體如下:
push()方法
1. 定義:向數(shù)組的末尾添加一個或更多元素,并返回新的長度。
2. 語法: arr.push(element1, ..., elementN)
3. 參數(shù):可以接收任意個數(shù)量的參數(shù)
4. 返回值:返回修改后數(shù)組的長度。
var arr1 = [1, 2, 3, 4]; var arr2 = ["C", "B", "A"]; Array.prototype.copyPush = function() { for(var i = 0; i < arguments.length; i++) { this[this.length] = arguments[i]; } return this.length; }; console.log(arr1.push('A', 'B')); // 6 console.log(arr1); // [1, 2, 3, 4, 'A', 'B'] console.log(arr2.push()); // 3 console.log(arr2); // ["C", "B", "A"]
運行結(jié)果:
pop()方法
1. 定義:從數(shù)組末尾移除最后一項,減少數(shù)組的length值,并返回移除的項。
2. 語法: arr.pop()
3. 參數(shù):/
4. 返回值:從數(shù)組中刪除的元素(當(dāng)數(shù)組為空時返回undefined)。
var arr1 = [1, 2, 3, 4]; var arr2 = []; Array.prototype.copyPop = function() { var result = null; if(this.length == 0) { //數(shù)組為空時返回undefined return undefined; } result = this[this.length - 1]; this.length = this.length - 1; return result; }; console.log(arr1.copyPop()); // 4 console.log(arr1); // [1, 2, 3] console.log(arr1.length); // 3 // 數(shù)組為空時 console.log(arr2.length); // 0 console.log(arr2.copyPop()); // undefined console.log(arr2); // [] console.log(arr2.length); // 0
運行結(jié)果:
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)組操作技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《javascript面向?qū)ο笕腴T教程》、《JavaScript數(shù)學(xué)運算用法總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript錯誤與調(diào)試技巧總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
相關(guān)文章
Javascript的常規(guī)數(shù)組和關(guān)聯(lián)數(shù)組對比小結(jié)
關(guān)聯(lián)數(shù)組雖然可以用字符串作下標(biāo),但是這個下標(biāo)是不支持參數(shù)傳值的,換言之,你需要什么就取什么,聽起來很智能,實際上你取值仍然需要你手動去寫下標(biāo)的2012-05-05使用 JScript 創(chuàng)建 .exe 或 .dll 文件的方法
JScript 是由微軟開發(fā)的活動腳本語言,基于 ECMAScript 規(guī)范實現(xiàn)。Internet Explorer 中的 JavaScript,實際上是指 JScript。2011-07-07json_decode 索引為數(shù)字時自動排序問題解決方法
這篇文章主要介紹了使用son_encode 給前端返回數(shù)據(jù),結(jié)果順序不對,經(jīng)debug調(diào)試,發(fā)現(xiàn)是json_encode 函數(shù)的問題,變成 " " + 數(shù)字即可,需要的朋友可以參考下2020-03-03