以下是我迄今为止的JavaScript代码:

var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 
linkElement.appendChild(newT);

目前,它从URL中获取数组中倒数第二项。但是,我想检查数组中的最后一个项目是否为“index.html”,如果是这样,则获取倒数第三个项目。


当前回答

“最干净”的ES6方式(IMO)是:

const foo = [1,2,3,4];
const bar = [...foo].pop();

这避免了像.pop()那样改变foo,如果我们不使用spread运算符。也就是说,我也喜欢foo.slice(-1)[0]解决方案。

其他回答

根据ES2022,您可以使用Array.at()方法,该方法获取一个整数值并返回该索引处的项。允许正整数和负整数。负整数从数组中的最后一项开始倒数。

演示:

const href='www.abc.com/main/index.html';constloc_array=href.split('/');//要访问数组中的元素,我们可以使用array.at()console.log(loc_array.at(-1));//这将返回最后一个索引处的项目。

还有一个npm模块,将最后一个添加到Array.prototype

npm install array-prototype-last --save

用法

require('array-prototype-last');

[1, 2, 3].last; //=> 3 

[].last; //=> undefined 

对于那些不怕重载Array原型的人(使用枚举掩码,您不应该这样做):

Object.defineProperty( Array.prototype, "getLast", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 1 ];
    }
} );

ES6对象销毁是另一种方法。

常量{length,[length-1]:last}=[1,2,3,4,5]console.log(最后一个)

使用对象析构函数从Array中提取长度属性。您可以使用按[length-1]提取的密钥创建另一个动态密钥,并将其分配给最后一个,全部在一行中。

如果想要一次性获得最后一个元素,可以使用Array#splice():

lastElement = document.location.href.split('/').splice(-1,1);

这里,不需要将拆分的元素存储在数组中,然后获取最后一个元素。如果获得最后一个元素是唯一的目标,那么应该使用这个。

注意:这将通过删除最后一个元素来更改原始数组。将splice(-1,1)看作弹出最后一个元素的pop()函数。