手写数组方法(十八):pop

316 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第26天,点击查看活动详情

前两天写了pushunshift方法,今天来讲讲pop

语法

arr.pop()

pop 方法从一个数组中删除并返回最后一个元素。

返回值

从数组中删除的元素(当数组为空时返回undefined)。

例子

let list = [1, 2, 3];
list.pop();

image.png

当数组为空时:

let list = [];
list.pop();

image.png

call,apply一起使用:

let fruits = ['apple', 'orange', 'banana'];
Array.prototype.pop.apply(fruits);

image.png

let fruits = ['apple', 'orange', 'banana'];
Array.prototype.pop.call(fruits);

image.png

let fruit = {name: 'apple', weight: '300g', length: 3};
Array.prototype.pop.call(fruit);

image.png

pop 方法有意具有通用性。该方法和 call 或 apply 一起使用时,可应用在类似数组的对象上。pop 方法根据 length 属性来确定最后一个元素的位置。如果不包含 length 属性或 length 属性不能被转成一个数值,会将 length 置为 0,并返回 undefined

手写

Array.prototype._pop = function() {
    if(!this.length) return undefined;
    let res = this[this.length - 1];
    this.length -= 1;
    return res;
}

image.png

哇,今天的手写是最简单的一次了,so 他妈 easy,我都以为我悟了~

应用

在日常开发中,有种场景需要你删除数组最后一个元素,还得把它保存起来,那这时候用pop是不二选择。不然你还得定义一个变量等于数组最后一个元素,多此一举。

结语

今天关于数组pop的介绍就讲到这里,关注我获取更多有关数组方法的讲解,后续会持续更新。我是末世未然,一个爱折腾的新晋奶爸,祝好