TIL | Slice & Splice

ryan·2020년 11월 18일
0

JavaScript

목록 보기
8/23
post-thumbnail

➕ More Array Methods

  • slice - copies a portion on an array
  • splice - removes/replaces elements
  • sort - sorts an array

🧬 slice() - copies a portion on an array

let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

colors.slice(); // ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

colors.slice(3); // ["green", "blue", "indigo", "violet"]
colors.slice(5); // ["indigo", "violet"]
colors.slice(1); // ["orange", "yellow", "green", "blue", "indigo", "violet"]

let coolColors = colors.slice(3);
coolColors; // ["green", "blue", "indigo", "violet"]

colors // ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

colors.slice(2, 4); // ["yellow", "green"]
colors.slice(0, 3); // ['red', 'orange', 'yellow']

let warmColors = colors.slice(0,3);
warmColors; // ['red', 'orange', 'yellow']

colors // ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

colors.slice(-3); // ['blue', 'indigo', 'violet'];
colors.slice(-2); // ['indigo', 'violet'];

🔧 splice - removes/replaces elements

let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

colors.splice(5, 1) // ["indigo"]
colors // ["red", "orange", "yellow", "green", "blue", "violet"]


let days = ["Monday", "Tuesday", "Wednesday"]

days.splice(1, 2); // ["Tuesday", "Wednesday"]
days // ["Monday"]


colors // ["red", "orange", "yellow", "green", "blue", "violet"]

colors.splice(1, 0, 'red-orange') // []
colors // ["red", "red-orange", "orange", "yellow", "green", "blue", "violet"]

colors.splice(4, 0, 'yellow-green', 'forestgreen') // []
colors // ["red", "red-orange", "orange", "yellow", "yellow-green", "forestgreen", "green", "blue", "violet"]

🧂 sort - sorts an array

let scores = [1, 70, 100, 2500, 9, -12, 0, 34]

scores.sort() // [-12, 0, 1, 100, 2500, 34, 70, 9]
// ???
profile
👨🏻‍💻☕️ 🎹🎵 🐰🎶 🛫📷

0개의 댓글