JavaScript의 Array methods

Sanghun Kim·2021년 4월 18일
0

Add and Remove elements from an array (Mutable)

let nums = [1,2,3,4,5];

// Add an element to the end of the array
nums.push(6); // = > nums === [1,2,3,4,5,6]

// Remove an element from the end of the array
nums.pop(); // => nums === [1,2,3,4,5] it returns popped value 6

// Add an element to the biginning of the array
nums.unshift(0); // => nums === [0,1,2,3,4,5]

// Remove an element from the biginning of the array
nums.shift(); // => nums === [1,2,3,4,5]

// Return the number of elements in the array
nums.length; // => 5


Check if it is an array

let label = 'orders';
let nums = [1,2,3,4,5];

Array.isArray(nums); // => true

Array.isArray(label); // => false


Check if an array includes a specified value

let words = ['hi','my','name','is','hun'];

//Get the index of a specified value if it is included in the array
words.indexOf('hi'); // => 0
words.indexOf('is'); // => 3
words.indexOf('no'); // => -1  it returns -1 if the value is not included

//Check if the array includes the value or not
words.includes('hi'); // => true
words.includes('no'); // => false

** includes는 Internet Explorer에서 지원하지 않을 뿐 아니라, indexOf를 사용하면 index에 대한 정보까지 얻을 수 있기때문에 indexOf의 사용을 권장



Slice and join an array (Immutable)

let nums = [0,1,2,3,4,5,6,7,8,9];

nums.slice(0,5); //return an array as [0,1,2,3,4] from first index to just before the second index
nums.slice(4); // return [4,5,6,7,8,9] from the index to the end
nums.slice(4).join(''); // return '456789' concat all the elements with the argument in join method
nums.slice(6).join('-'); // return '6-7-8-9'
nums; // return [0,1,2,3,4,5,6,7,8,9] coz the slice method doesn't change the original array


profile
코드스테이츠 소프트웨어 엔지니어링 29기

0개의 댓글