【JavaScript 教程】第六章 數(shù)組20—pop() :從數(shù)組末尾刪除一個元素

來源 | https://www.javascripttutorial.net/
翻譯 | 楊小愛
在今天的文章教程中,我們將一起來學(xué)習(xí)如何使用 JavaScript Array pop() 方法從數(shù)組中刪除最后一個元素。
JavaScript Array pop() 方法介紹
Array.prototype.pop() 方法從數(shù)組中移除最后一個元素并返回移除的元素, 下面是 pop() 方法的語法:
array.pop()
pop() 方法更改數(shù)組的長度屬性,如果數(shù)組為空,pop() 將返回 undefined。
JavaScript pop() 方法示例
讓我們舉一些使用 pop() 方法的例子。
1) 使用 JavaScript 數(shù)組 pop() 方法刪除數(shù)組的最后一個元素
以下示例使用 pop() 方法刪除 numbers 數(shù)組的最后一個元素:
const numbers = [10, 20, 30];const last = numbers.pop();console.log(last); // 30console.log(numbers.length); // 2
輸出:
302
在此示例中,pop() 方法從 numbers 數(shù)組中刪除數(shù)字 30。此外,它會將 numbers 數(shù)組的 length 屬性的值減小到 2。
下圖說明了 pop() 方法的工作原理:

2) 對空數(shù)組使用 JavaScript 數(shù)組 pop() 方法
以下示例在空數(shù)組上調(diào)用 pop() 方法。在這種情況下,pop() 方法返回 undefined 并且數(shù)組的長度為零:
const numbers = [];const last = numbers.pop();console.log(last);console.log(numbers.length);
輸出:
undefined0
對類數(shù)組對象使用 JavaScript pop() 方法
pop() 方法是通用的,因此,你可以使用 call() 或 apply() 來調(diào)用類數(shù)組對象的 pop() 方法。在內(nèi)部,pop() 使用類數(shù)組對象的長度屬性來確定要刪除的最后一個元素。
請參見以下示例:
let greetings = {0: 'Hi',1: 'Hello',2: 'Howdy',length: 2,removeLast() {return [].pop.call(this);},};let greting = greetings.removeLast();console.log(greting);console.log(greetings);
輸出:
'Howdy'{'0': 'Hi','1': 'Hello',length: 2,removeLast: [Function: removeLast]}
這個怎么運(yùn)作。
首先,定義有以下內(nèi)容的問候?qū)ο螅?/span>
四個屬性 0、1、2 和長度。
一種方法 removeLast() 使用數(shù)組的 call() 方法來調(diào)用 pop() 方法。
其次,調(diào)用 greetings 對象的 removeLast() 方法:
let greting = greetings.removeLast();
第三,將移除的元素(greeting)和greetings對象輸出到控制臺:
console.log(greting);console.log(greetings);
使用 pop() 方法刪除數(shù)組的最后一個元素。 使用 call() 或 apply() 在類數(shù)組對象上調(diào)用 pop() 方法。
相關(guān)教程
【JavaScript 教程】第六章 數(shù)組19—unshift() :將一個或多個元素添加到數(shù)組的開頭
【JavaScript 教程】第六章 數(shù)組18—push() :將一個或多個元素添加到數(shù)組的末尾
【JavaScript 教程】第六章 數(shù)組17—flatMap() :對每個元素執(zhí)行映射函數(shù)并將結(jié)果展平
【JavaScript 教程】第六章 數(shù)組16—flat() :遞歸地將數(shù)組展平到指定的深度
【JavaScript 教程】第六章 數(shù)組15—join() :將所有元素連接成一個字符串
【JavaScript 教程】第六章 數(shù)組14—reduce() :將數(shù)組的元素減少為一個值
【JavaScript 教程】第六章 數(shù)組13— forEach() :遍歷數(shù)組元素
【JavaScript 教程】第六章 數(shù)組12— map() :轉(zhuǎn)換數(shù)組元素
【JavaScript 教程】第六章 數(shù)組11— filter() :過濾數(shù)組中的元素
【JavaScript 教程】第六章 數(shù)組10— sort() :對數(shù)組中的元素進(jìn)行排序
【JavaScript 教程】第六章 數(shù)組09— some() :檢查數(shù)組中是否至少有一個元素通過了測試
【JavaScript 教程】第六章 數(shù)組08— every() :檢查數(shù)組中的每個元素是否都通過了測試
【JavaScript 教程】第六章 數(shù)組07— index() :在數(shù)組中定位一個元素
【JavaScript 教程】第六章 數(shù)組06— slice() :復(fù)制數(shù)組元素
【JavaScript 教程】第六章 數(shù)組05— splice():刪除、插入和替換
【JavaScript 教程】第六章 數(shù)組03— Stack :使用 Array 的push()和pop()方法實現(xiàn)堆棧數(shù)據(jù)結(jié)構(gòu)
【JavaScript 教程】第六章 數(shù)組02— Array Length:如何有效地使用數(shù)組的長度屬性
【JavaScript 教程】第六章 數(shù)組01— 介紹JavaScript中的Array類型
學(xué)習(xí)更多技能
請點擊下方公眾號
![]()

