以下是我迄今为止的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对象销毁是另一种方法。

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

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

其他回答

这行吗?

if (loc_array.pop() == "index.html"){
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-3])));
}
else{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}

编辑:

最近,我又提出了一个解决方案,我现在认为这是最适合我的需求的:

function w(anArray) {
  return {
    last() {
      return anArray [anArray.length - 1];
    };
  };
}

根据上述定义,我现在可以说:

let last = w ([1,2,3]).last();
console.log(last) ; // -> 3

名称“w”代表“包装器”。您可以看到如何轻松添加更多除了“last()”之外的方法。

我说“最符合我的需要”,因为这允许我可以很容易地添加其他这样的“助手方法”任何JavaScript内置类型。发生了什么记住Lisp的car()和cdr()例子

这可以用lodash _.last或_.nth完成:

var数据=[1,2,3,4]var last=_.nth(数据,-1)console.log(最后一个)<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js“></script>

我宁愿使用array.pop()而不是索引。

while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

通过这种方式,您总是得到index.html之前的元素(假设您的数组将index.html作为一个项目)。注意:您将丢失数组中的最后一个元素。

以下是如何在不影响原始阵列的情况下获得它

a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements

如果使用pop(),它将修改数组

a.pop();  // will return "abc" AND REMOVES IT from the array 
a.length; // returns 7

但您可以使用它,这样它对原始阵列没有影响:

a.slice(-1).pop(); // will return "abc" won't do modify the array 
                   // because slice creates a new array object 
a.length;          // returns 8; no modification and you've got you last element