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


当前回答

我建议您创建助手函数,并在每次需要时重用它。让我们让函数更通用,以便不仅可以获取最后一项,还可以获取倒数第二项,依此类推。

function last(arr, i) {
    var i = i || 0;
    return arr[arr.length - (1 + i)];
}

用法很简单

var arr = [1,2,3,4,5];
last(arr);    //5
last(arr, 1); //4
last(arr, 9); //undefined

现在,让我们解决最初的问题

从数组中抓取倒数第二项。如果loc_array中的最后一个项目是“index.html”,则抓取倒数第三个项目。

下一行完成任务

last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);

所以,你需要重写

var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 

以这种方式

var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1)))); 

或使用附加变量来增加可读性

var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));

其他回答

就我个人而言,我会支持库波里菲奇·克里齐克拉茨的回答。如果使用嵌套数组,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]

通过使用带负值的切片方法可以获得数组的最后一项。

你可以在底部阅读更多关于它的信息。

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

使用pop()将改变数组,这并不总是一个好主意。

要防止从原始阵列中删除最后一项,可以使用

Array.from(myArray).pop()

主要支持所有浏览器(ES6)

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

我通常使用underscorejs,有了它你就可以

if (_.last(loc_array) === 'index.html'){
  etc...
}

对我来说,这比loc_array.slice(-1)[0]更具语义