IT/WILT

[JavaScript] 8. Array

KimCookieYa 2022. 2. 25. 02:03

 

1.  Array Declaration

'use strict';

const arr1 = new Array();
const arr2 = [1, 2];

 

 

2. Index position

const fruits = ['apple', 'banana'];
console.log(fruits); // ['apple', 'banana']
console.log(fruits.length); // 2
console.log(fruits[0]); // apple
console.log(fruits[1]); // banana
console.log(fruits[2]); // undefined

 

 

3. Looping over an array

for (let i = 0; i < fruits.length; i++) { // for
	console.log(fruits[i]);
} // apple banana

for (let fruit of fruits) { // for of
	console.log(fruit);
} // apple banana

fruits.forEach(function (fruit, index, array) {
	console.log(fruit, index, array);
}); // 아래처럼 생략가능

fruits.forEach((fruit) => console.log(fruit));

 

 

4. Addition, Deletion and Copy

 - push: add an item to the end.

 - pop: remove an item from the end.

 - unshift: add an item to the begining.

 - shift: remove an item from the begining.

 - shift, unshift are slower than pop, push.

- splice: remove an item by index position.

fruits.push('berry');
fruits.pop();
fruits.unshift('lemon');
fruits.shift();
fruits.splice(1, 1); // .splice(startIndex, deleteCount)

 

4-1. combine two arrays

const fruits2 = ['grape', 'mog'];
const newFruits = fruits.concat(fruits2);

 

 

5. Searching

 - find the index.

console.log(fruits.indexOf('apple'); // 0
console.log(fruits.indexOf('banana'); // 1

console.log(fruits.includes('banana'); // true
console.log(fruits.includes('grape'); // false

fruits.push('apple');
console.log(fruits); // ['apple', 'banana', 'lemon', 'apple']
console.log(fruits.lastIndexOf('apple'); // 3