十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章給大家介紹JavaScript中push()和pop()方法如何使用,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

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')); // 6console.log(arr1); // [1, 2, 3, 4, 'A', 'B']console.log(arr2.push()); // 3console.log(arr2); // ["C", "B", "A"]
運(yùn)行結(jié)果:
1. 定義:從數(shù)組末尾移除最后一項(xiàng),減少數(shù)組的length值,并返回移除的項(xiàng)。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()); // 4console.log(arr1); // [1, 2, 3]console.log(arr1.length); // 3// 數(shù)組為空時console.log(arr2.length); // 0console.log(arr2.copyPop()); // undefinedconsole.log(arr2); // []console.log(arr2.length); // 0
關(guān)于JavaScript中push()和pop()方法如何使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。