Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 获取数组最后一位

作者:不,完美   发布日期:2026-06-18   浏览:69

// 获取数组最后一位的几种方法

// 方法一:使用数组的 length 属性
const arr = [1, 2, 3, 4, 5];
const lastElement = arr[arr.length - 1];
console.log(lastElement); // 输出: 5

// 方法二:使用数组的 at 方法(现代浏览器支持)
const lastElementAt = arr.at(-1);
console.log(lastElementAt); // 输出: 5

// 方法三:使用 pop 方法(会改变原数组)
const lastElementPop = arr.pop();
console.log(lastElementPop); // 输出: 5
console.log(arr); // 输出: [1, 2, 3, 4]

解释说明:

  1. 方法一:通过 arr.length - 1 获取数组的最后一个索引,然后访问该索引对应的元素。
  2. 方法二:使用 at 方法可以直接通过负数索引来获取数组中的元素,-1 表示最后一个元素。注意,at 方法在较老的浏览器中可能不被支持。
  3. 方法三:使用 pop 方法可以移除并返回数组的最后一个元素,但这种方法会改变原数组。

上一篇:js 获取数组下标

下一篇:js 循环字符串

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站