---
# System prepended metadata

title: .at()

---

# .at()
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at) | [codepen](https://codepen.io/kentyangfake/pen/xxaZzez)

主要是用來處理倒數,`arr.at(-1)`
#### 跟arr[-1]的差別
因為JS的arr也是object,`arr[-1]`會return undefined, '-1'會被處理成string,所以可以想成arr.'-1'會取出一個沒指定的值
* `[ ]` 是一種運算子（operator）, 程式會計算出這個索引對應的位置，然後將該位置的元素回傳給你。如果索引值超出了陣列的範圍，程式會拋出一個例外（undefined）
* 一般使用`arr[arr.length-1]`取值
```
arr.at(-1) === arr[arr.length-1] === arr.slice(-2, -1)
```
#### 處理array-like
```
let arr = {
0: 'a',
1: 'b',
length: 2
}
```
* string
* 與 DOM 元素相關的 JavaScript 程式中:
Nodelist: document.querySelectorAll('')回傳的東西,不適用部分array method,要先用Array.from()轉成陣列
```
let category = document.querySelectorAll('.category');

Array.from(category).at(-1);
```
#### 應用
```
const users = ["amy","benson","cathy"];
let currentNum = 0;
let prevNum;

setInterval(() => {
  currentNum = (currentNum + 1) % users.length;
  showPrevUser();
}, 3000);

function showPrevUser() {
  prevNum = currentNum - 1;
  let user = users.at(prevNum);
  console.log(`current: ${currentNum}, prev: ${prevNum} user: ${user}`);
}
```
## Styled component
[Docs](https://styled-components.com/docs) | [Basic](https://codepen.io/kentyangfake/pen/QWVyVLr) | [ThemeProvider](https://codepen.io/kentyangfake/pen/abademo?editors=0010)
## Figma Jam
[首頁架構圖](https://www.figma.com/file/0dvdwoQF3hERLCXKJlz8H2/%E9%A6%96%E9%A0%81%E6%9E%B6%E6%A7%8B?t=Gua58HTt2LbSTtlS-0)