Array

heyj·2022년 1월 25일
0

HTML/CSS/Javascript

목록 보기
4/8
post-thumbnail

1. Declaration

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

2. Index position

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

3. Looping over an array

// print all fruits

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

// b. for of
for (let fruit of fruits) {
    console.log(fruit); // apple, orange
}

// c. forEach
fruits.forEach((fruit) => console.log(fruit));   // apple, orange

4. Addtion, deletion, copy

// push: add an item to the end
fruits.push('banana', 'pear');
console.log(fruits);  // [ 'apple', 'orange', 'banana', 'pear' ]

// pop: remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits);  // ['apple', 'orange']

// unshift: add an item to the beginnig
fruits.unshift('strawberry', 'lemon');
console.log(fruits);    // [ 'strawberry', 'lemon', 'apple', 'orange' ]

// shift: remove and item from the beginnig
fruits.shift();
fruits.shift();
console.log(fruits);  // [ 'apple', 'orange' ]

// note! shift, unshift are slower than pop, push
// splice: remove an item by index position
fruits.push('strawberry', 'lemon', 'pear');
console.log(fruits);  // [ 'apple', 'orange', 'strawberry', 'lemon', 'pear' ]
fruits.splice(1, 1);
console.log(fruits);  // [ 'apple', 'strawberry', 'lemon', 'pear' ]
fruits.splice(1, 1, 'grape', 'watermelon');
console.log(fruits);  // [ 'apple', 'grape', 'watermelon', 'lemon', 'pear' ]

//combine two arrays
const fruits2 = ['melon', 'tomato'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits); // [ 'apple', 'grape', 'warermelon', 'lemon', 'pear', 'melon', 'tomato' ]

5. Searching

// indexOf: find the index
console.log(fruits);  // [ 'apple', 'grape', 'warermelon', 'lemon', 'pear' ]
console.log(fruits.indexOf('apple')); // 0
console.log(fruits.indexOf('watermelon')); // -1
console.log(fruits.indexOf('pear')); // 4

// includes
console.log(fruits.includes('kiwi')); // false
console.log(fruits.includes('watermelon')); // false

// lastIndexOf
fruits.push('apple');
console.log(fruits); [ 'apple', 'grape', 'warermelon', 'lemon', 'pear', 'apple' ]
console.log(fruits.lastIndexOf('apple')); // 5

0개의 댓글