Created
October 29, 2019 01:48
-
-
Save rodurma/561fc40cbf42a825404e44c1e91280f2 to your computer and use it in GitHub Desktop.
Várias maneiras de pegar o primeiro e último elemento de um array com JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// considerando o array abaixo | |
const arr = [4, 7, 10, 82, 35]; | |
// Opção 1: Pelo tamanho do array | |
let first = arr[0]; | |
let last = arr[arr.length-1]; | |
// Opção 2: Com shift(), pop() e Spread operator | |
let first = [...arr].shift(); | |
let last = [...arr].pop(); | |
// Opção 3: Desestruturação | |
let {length, 0: first, [length-1]: last} = arr; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment