Array Methods Flashcards
arr.push
Adds items to the end
arr.push(…items)
arr.pop()
Take away an item from the end
arr.shift()
takes away item from the beginning
arr.unshift()
adds item to the beginning
arr.unshift(…items)
splice()
swiss army knives of arrays- can insert, remove, and replace elements
arr.splice(start, delete, replace/insert)
returns array of removed elements
ex: let arr = [“I”, “study”, “JavaScript”, “right”, “now”];
// remove 2 first elements
let removed = arr.splice(0, 2);
alert( removed ); // “I”, “study” <– array of removed elements
let arr = [“I”, “study”, “JavaScript”];
// from index 2
// delete 0
// then insert “complex” and “language”
arr.splice(2, 0, “complex”, “language”);
alert( arr ); // “I”, “study”, “complex”, “language”, “JavaScript”
Negative indexes: specify position from end of array
arr.slice()
returns new array copying all items passed as parameters
arr.slice(start, end)
arr.slice() by itself creates a copy– used to make a copy and make changes
arr.concat()
creates a new array that includes values from other arrays and additional items
arr.concat(arg1, arg2…)
takes arrays and values as arguments
can’t pass objects unless use: Symbol.isConcatSpreadable property -> treated like an array
Symbol.isConcatSpreadable
Used so objects can be concatenated
let arr = [1, 2];
let arrayLike = {
0: “something”,
1: “else”,
[Symbol.isConcatSpreadable]: true,
length: 2
};
alert( arr.concat(arrayLike) ); // 1,2,something,else