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


当前回答

就我个人而言,我会支持库波里菲奇·克里齐克拉茨的回答。如果使用嵌套数组,array[array.length-1]方法会变得非常难看。

var array = [[1,2,3], [4,5,6], [7,8,9]]
​
array.slice(-1)[0]
​
//instead of 
​
array[array.length-1]
​
//Much easier to read with nested arrays
​
array.slice(-1)[0].slice(-1)[0]
​
//instead of
​
array[array.length-1][array[array.length-1].length-1]

其他回答

您也可以在不从url中提取数组的情况下实现此问题

这是我的选择

var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();

!问候语

如果你来这里找的话,这里还有更多的Javascript艺术

根据另一个使用reduceRight()但更短的答案:

[3, 2, 1, 5].reduceRight(a => a);

它依赖于这样一个事实,即如果您没有提供初始值,最后一个元素将被选为初始元素(请查看此处的文档)。由于回调只返回初始值,最后一个元素将是最后返回的元素。

请注意,这应该被认为是Javascript的艺术,而不是我推荐的方式,主要是因为它在O(n)时间运行,但也因为它会损害可读性。

现在是严肃的答案

我认为最好的方法(考虑到您希望它比array[array.length-1]更简洁)是:

const last = a => a[a.length - 1];

然后只需使用函数:

last([3, 2, 1, 5])

如果您正在处理上面使用的[3,2,1,5]这样的匿名数组,则该函数实际上非常有用,否则您必须将其实例化两次,这将是低效且丑陋的:

[3, 2, 1, 5][[3, 2, 1, 5].length - 1]

Ugh.

例如,在这种情况下,您有一个匿名数组,您必须定义一个变量,但您可以使用last()代替:

last("1.2.3".split("."));

通常情况下,你不应该搞乱内置类型的原型,但这里有一个破解/快捷方式:

Object.defineProperty(Array.prototype, 'last', {
  get() {
    return this[this.length - 1]; 
  }
});

这将允许所有数组对象具有最后一个属性,您可以这样使用:

const letters = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.last); // 'e'

您不应该使用内置类型的原型,因为您永远不会发布新的ES版本,如果新版本使用与自定义属性相同的属性名称,则可能会发生各种中断。此外,这会使其他人很难遵循您的代码,特别是对于加入团队的人。您可以将属性设置为您知道ES版本永远不会使用的属性,例如listLastItem,但这由开发人员自行决定。

或者您可以使用一个简单的方法:

const getLast = (list) => list[list.length - 1];
const last = getLast([1,2,3]); // returns 3

为了获得一个可读且简洁的解决方案,可以使用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);

不确定是否存在缺陷,但这似乎相当简洁:

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

如果数组为空,则两者都将返回undefined。