본문 바로가기

Programming/JavaScript

Basic Array Operations (Methods)

const friends = ['Michael', 'Steven', 'Peter'];
friends.push('Jay');
console.log(friends);
// prints  ['Michael', 'Steven', 'Peter', 'Jay']

Add elements

const friends = ['Michael', 'Steven', 'Peter'];
const newLength = friends.push('Jay');
console.log(newLength);
// prints 4
friends.unshift('John');
console.log(friends);
// prints ['John', 'Michael', 'Steven', 'Peter', 'Jay']

unshift() method is used to add one or more elements to the beginning of the given array. This function increases the length of the existing array by the number of elements added to the array.

 

JavaScript Array unshift() Method - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

Remove elements

friends.pop(); // Remove the last element
friends.pop();
console.log(friends);
// prints ['John', 'Michael', 'Steven']
friends.pop(); // Remove the last element
const popped = friends.pop();
console.log(popped);
// prints Peter
console.log(friends);
// prints  ['John', 'Michael', 'Steven']
friends.shift(); // First
console.log(friends);
// prints ['Michael', 'Steven']

console.log(friends.indexOf('Steven'));
// prints 1
friends.push(23);
console.log(friends.includes('Steven')); // true
console.log(friends.includes('Bob')); // false
console.log(friends.includes('23')); //  false

23은 string이고 23은 number이기 때문에

false값이 나온거임

console.log(friends.includes(23)); // true
if (friends.includes('Steven')) {
    console.log('You have a friend called Steven');
}
// prints You have a friend called Steven

'Programming > JavaScript' 카테고리의 다른 글

Introduction to Objects  (0) 2022.09.11
Coding Challenge #2 - tip calculator with arrays  (0) 2022.09.10
Introduction to Arrays  (0) 2022.09.10
Coding Challenge #1 - who's win?  (0) 2022.09.09
Reviewing Functions  (0) 2022.09.05