Js陣列最後一個

在JavaScript中,可以使用陣列的length屬性來取得陣列的最後一個元素。以下是如何取得陣列最後一個元素的幾種方法:

方法1:使用length屬性和索引運運算元

let array = ['a', 'b', 'c'];
let lastElement = array[array.length - 1];
console.log(lastElement); // 輸出 'c'

方法2:使用Array.prototype.slice方法

let array = ['a', 'b', 'c'];
let lastElement = array.slice(-1)[0];
console.log(lastElement); // 輸出 'c'

方法3:使用Array.prototype.pop方法

let array = ['a', 'b', 'c'];
let lastElement = array.pop();
console.log(lastElement); // 輸出 'c'

方法4:使用Array.prototype.shift方法

let array = ['a', 'b', 'c'];
let lastElement = array.shift();
console.log(lastElement); // 輸出 'a'

注意,Array.prototype.shift方法會移除並返回陣列的第一個元素,而不是最後一個元素。如果你想要取得陣列的第一個元素,可以使用Array.prototype.shift方法,然後將返回的值賦給一個變數。