到目前爲止,這是個人JavaScript代碼: html
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.pop : app
var lastItem = anArray.pop();
重要提示 :這將返回最後一個元素並將其從數組中刪除 this
不知道是否有缺點,但這彷佛很簡潔: spa
arr.slice(-1)[0]
要麼 prototype
arr.slice(-1).pop()
若是數組爲空,則二者都將返回undefined
。 code
對於那些不怕重載Array原型的人(而且不該該使用枚舉掩碼 ): htm
Object.defineProperty( Array.prototype, "getLast", { enumerable: false, configurable: false, writable: false, value: function() { return this[ this.length - 1 ]; } } );
@chaiguy發佈的內容的簡短版本: 索引
Array.prototype.last = function() { return this[this.length - 1]; }
讀取-1索引已返回undefined
。 ip
編輯:
這些天來,人們彷佛傾向於使用模塊,以免接觸原型或使用全局名稱空間。
export function last(array) { return array[array.length - 1]; }
經過使用帶負值的slice方法,能夠獲取數組的最後一項。
你能夠閱讀更多關於它在這裏的底部。
var fileName = loc_array.slice(-1)[0]; if(fileName.toLowerCase() == "index.html") { //your code... }
使用pop()會更改數組,但這並不老是一個好主意。