以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。


当前回答

const [y] = x.slice(-1)

快速解释:这种语法[y]=<array/object>被称为destructuring赋值&根据Mozilla文档,destructoring赋值可以将数组中的值或对象中的财产解包为不同的变量阅读更多信息:此处

其他回答

要使用c#访问数组中的最后一个元素,我们可以使用GetUpperBound(0)

(0)如果此一维数组

my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array

对于那些不怕重载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]提取的密钥创建另一个动态密钥,并将其分配给最后一个,全部在一行中。

if (loc_array[loc_array.length - 1] === 'index.html') {
   // do something
} else {
   // something else
}

如果您的服务器为“index.html”和“index.html”提供相同的文件,您也可以使用:.toLowerCase()。

不过,如果可能的话,您可能会考虑在服务器端做这件事:它会更干净,适用于没有JS的人。


编辑-ES-2022

使用ES-2022 Array.at(),上面的内容可以这样写:

if (loc_array.at(-1) === 'index.html') {
   // do something
} else {
   // something else
}

可以通过长度属性获取最后一项。由于数组计数从0开始,因此可以通过引用array.length-1项来拾取最后一项

常量arr=[1,2,3,4];常量last=arr[arr.length-1];console.log(最后一个);//4.

另一个选项是使用新的Array.prototype.at()方法,该方法接受一个整数值并返回该索引处的项。负整数从数组中的最后一项开始倒数,所以如果我们想要最后一项,我们只需传入-1

常量arr=[1,2,3,4];常量last=arr.at(-1);console.log(最后一个);//4.

另一个选项是使用新的findLast方法。你可以在这里看到提案

常量arr=[1,2,3,4];const last=arr.findLast(x=>true);console.log(最后一个);//4.

另一个选项是使用Array.prototype.slice()方法,该方法将数组的一部分的浅拷贝返回到新的数组对象中。

常量arr=[1,2,3,4];常量last=arr.slice(-1)[0];console.log(最后一个);//4.