以下是我迄今为止的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.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);

其他回答

这样既干净又高效:

let list = [ 'a', 'b', 'c' ]

(xs => xs[xs.length - 1])(list)

如果您使用Babel安装管道操作员,它将变为:

list |> (xs => xs[xs.length - 1])

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

npm install array-prototype-last --save

用法

require('array-prototype-last');

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

[].last; //=> undefined 

在javascript中查找数组最后一个值的多种方法

不影响原始阵列

var arr=[1,2,3,4,5];控制台日志(arr.slice(-1)[0])控制台日志(arr[arr.length-1])const[last]=[…arr].reverse();console.log(最后一个)让copyArr=[…arr];console.log(copyArr.reverse()[0]);

修改原始阵列

var arr=[1,2,3,4,5];console.log(arr.pop())arr.push(5)console.log(…arr.splice(-1));

通过创建自己的助手方法

设arr=[1,2,3,4,5];Object.defineProperty(arr,'last',{get:function(){返回this[this.length-1];}})控制台日志(arr.last);

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

这是我的选择

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

!问候语

array.reverse()[0]

太简单了