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

其他回答

const[lastItem]=array.sslice(-1);

带有-1的Array.prototype.slice可用于创建仅包含原始Array的最后一项的新Array,然后可以使用Destructuring Assignment使用该新Array的第一项创建变量。

常量彩票号码=[12,16,4,33,41,22];const[lastNumber]=lotteryNumbers.slice(-1);console.log(lotteryNumbers.slice(-1));// => [22]console.log(lastNumber);// => 22

您可以使用此模式。。。

let [last] = arr.slice(-1);

虽然它读起来很好,但请记住,它创建了一个新的阵列,因此效率比其他解决方案低,但它几乎永远不会成为应用程序的性能瓶颈。

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

使用lodash_.last(array)获取数组的最后一个元素。

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

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