迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中从数组中删除最后一个元素

作者:迹忆客 最近更新:2023/03/10 浏览次数:

数组将每个元素存储在特定索引处。元素的索引从 0 开始到数组长度减 1。

在本教程中,讨论了在 JavaScript 中从数组中删除最后一个元素的不同方法。

splice() 方法用于通过删除或替换元素来更改数组。如果删除了任何元素,则返回已删除的元素。否则,返回一个空数组。

我们可以使用它从数组中删除最后一个元素。

参考下面的代码。

var array = [10,11,12,13,14,15,16,17];
array.splice(-1,1);
console.log(array);

输出:

[10, 11, 12, 13, 14, 15, 16]

pop() 函数是实现此目的最直接的方法。它从数组中删除最后一个元素并返回删除的元素。

例如,

var array = [10,11,12,13,14,15,16,17];
array.pop();
console.log(array)

输出:

[10, 11, 12, 13, 14, 15, 16]

slice() 函数创建从 startstop(不包括结尾)中选择的定义部分的副本。startstop 值是数组的索引。它返回新数组。

参考下面的代码。

var array = [10,11,12,13,14,15,16,17];
array = array.slice(0,-1);
console.log(array);

输出。

[10, 11, 12, 13, 14, 15, 16]

filter() 方法根据传递的提供的函数返回修改后的数组。

要使用此函数删除最后一个元素,请参考下面的代码。

var array = [10,11,12,13,14,15,16,17];
array = array.filter((element, index) => index < array.length - 1);
console.log(array);

输出:

[10, 11, 12, 13, 14, 15, 16]

我们可以创建一个新函数,该函数将数组作为输入,如果数组的长度大于零,则减少数组的长度。

我们在下面的例子中实现了这一点。

var array = [10,11,12,13,14,15,16,17];

function removeElement(arr) {
  if(arr.length > 0)
    arr.length --;
  return arr
};

var newArray = removeElement(array);
console.log(newArray);

输出:

[10, 11, 12, 13, 14, 15, 16]

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便