以下是我迄今为止的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的原型中添加一个新的属性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时不工作。

其他回答

这个问题已经存在了很长一段时间,所以我很惊讶没有人提到在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的比率。然而,没有人喜欢资源猪。

编辑:

最近,我又提出了一个解决方案,我现在认为这是最适合我的需求的:

function w(anArray) {
  return {
    last() {
      return anArray [anArray.length - 1];
    };
  };
}

根据上述定义,我现在可以说:

let last = w ([1,2,3]).last();
console.log(last) ; // -> 3

名称“w”代表“包装器”。您可以看到如何轻松添加更多除了“last()”之外的方法。

我说“最符合我的需要”,因为这允许我可以很容易地添加其他这样的“助手方法”任何JavaScript内置类型。发生了什么记住Lisp的car()和cdr()例子

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

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

在ECMAScript建议阶段1中,建议添加一个数组属性,该属性将返回最后一个元素:proposal array last。

语法:

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

可以使用polyfill。

提案作者:Keith Cirkel(chai autor)

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