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
'IT > WILT' 카테고리의 다른 글
[JavaScript] 10. JSON (0) | 2022.03.02 |
---|---|
[JavaScript] 9. Array API (0) | 2022.02.26 |
[JavaScript] 7. Object (0) | 2022.02.24 |
[JavaScript] 6. 객체지향 언어, class VS object (0) | 2022.02.22 |
[JavaScript] 5. 함수의 선언과 표현, Arrow Function (0) | 2022.02.22 |