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


当前回答

此方法不会干扰原型。它还防止0长度数组以及空/未定义数组。如果返回的默认值可能与数组中的项相匹配,您甚至可以重写默认值。

常量项=[1,2,3]常量noItems=[]/***返回数组中的最后一项。*如果数组为null、undefined或空,则返回默认值。*/函数arrayLast(arrayOrNull,defVal=未定义){if(!arrayOrNull | | arrayOrNull.length==0){返回defVal}return arrayOrNull[arrayOrNull.length-1]}console.log(arrayLast(项))console.log(arrayLast(noItems))console.log(arrayLast(null))console.log(arrayLast(items,'someDefault'))console.log(arrayLast(noItems,'someDefault'))console.log(arrayLast(null,'someDefault'))

其他回答

如果想要一次性获得最后一个元素,可以使用Array#splice():

lastElement = document.location.href.split('/').splice(-1,1);

这里,不需要将拆分的元素存储在数组中,然后获取最后一个元素。如果获得最后一个元素是唯一的目标,那么应该使用这个。

注意:这将通过删除最后一个元素来更改原始数组。将splice(-1,1)看作弹出最后一个元素的pop()函数。

这个问题已经存在了很长一段时间,所以我很惊讶没有人提到在pop()之后重新打开最后一个元素。

arr.pop()的效率与arr[arr.length-1]完全相同,两者的速度都与arr.push()相同。

因此,您可以避免:

---已编辑[在推送前检查顶部是否未定义]---

let thePop = arr.pop()
thePop && arr.push(thePop)

---结束编辑---

可以降低到这个速度(相同速度[编辑:但不安全!]):

arr.push(thePop = arr.pop())    //Unsafe if arr empty

这是arr[arr.length-1]的两倍慢,但您不必到处填充索引。这在任何一天都是值得的。

在我尝试过的解决方案中,以arr[arr.length-1]的执行时间单位(ETU)的倍数表示:

[方法]。。。。。。。。。。。。。。[ETU 5元素]。。。[ETU 100万元]

arr[arr.length - 1]      ------> 1              -----> 1

let myPop = arr.pop()
arr.push(myPop)          ------> 2              -----> 2

arr.slice(-1).pop()      ------> 36             -----> 924  

arr.slice(-1)[0]         ------> 36             -----> 924  

[...arr].pop()           ------> 120            -----> ~21,000,000 :)

最后三个选项,特别是[…arr].pop(),随着数组大小的增加,会变得非常糟糕。在没有我的机器内存限制的机器上,[…arr].pop()可能会保持120: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);

这样既干净又高效:

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

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

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

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

您可以在Array的原型中添加一个新的属性getter,以便它可以通过Array的所有实例访问。

Getters允许您访问函数的返回值,就像它是属性的值一样。函数的返回值当然是数组的最后一个值(this[this.length-1])。

最后,将其包装在一个条件中,该条件检查最后一个属性是否仍然未定义(未由可能依赖它的另一个脚本定义)。

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

// Now you can access it like
[1, 2, 3].last;            // => 3
// or
var test = [50, 1000];
alert(test.last);          // Says '1000'

IE≤8时不工作。