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


当前回答

@chaiguy发布内容的简短版本:

Array.prototype.last = function() {
    return this[this.length - 1];
}

读取-1索引已返回undefined。

编辑:

如今,人们倾向于使用模块,避免接触原型或使用全局命名空间。

export function last(array) {
    return array[array.length - 1];
}

其他回答

可以在以下位置使用数组#的相对索引:

const myArray = [1, 2, 3]

console.log(myArray.at(-1))
// => 3
const lastElement = myArray[myArray.length - 1];

从性能角度来看,这是最佳选项(比arr.slice(-1)快1000倍左右)。

编辑:

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

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()例子

为了获得一个可读且简洁的解决方案,可以使用Array.prototype.slice和destructuring的组合。

const linkElement = document.getElementById("BackButton");
const loc_array = document.location.href.split('/');

// assign the last three items of the array to separate variables
const [thirdLast, secondLast, last] = loc_array.slice(-3);

// use the second last item as the slug...
let parentSlug = secondLast;

if (last === 'index.html') {
  // ...unless this is an index
  parentSlug = thirdLast;
}

const newT = document.createTextNode(
  unescape(
    capWords(parentSlug)
  )
);

linkElement.appendChild(newT);

但为了简单地获取数组中的最后一项,我更喜欢这种表示法:

const [lastItem] = loc_array.slice(-1);

jQuery巧妙地解决了这个问题:

> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined