티스토리 뷰

javascript

[Javascript] Array

tonirr 2020. 11. 9. 22:27
'use strict';

// Array

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

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

// 3. Looping over an array
// print all fruits
console.clear();
// a. for
for (let i = 0; i < fruits.length; i++){
    console.log(fruits[i]);
}

// b. for of 
for (let fruit of fruits) {
    console.log(fruit);
}
console.clear();
// c. forEach
fruits.forEach((fruits) => console.log(fruits));

// 4. Addtion, deletion, copy
// push: add an item to the end
fruits.push('strawberry', 'peach');
console.log(fruits);
// pop: remove an item from the end
fruits.pop();
console.log(fruits);
fruits.pop();
console.log(fruits);

// unshift: add an item to the beginning
fruits.unshift('strawberry', 'peach');
console.log(fruits);

// shift: remove an item from the beginning
fruits.shift();
fruits.shift();
console.log(fruits);

// note!! shift, unshift are slower than pop, push
// splice: remove an item by index position
fruits.push('strawberry', 'peach', 'lemon');
console.log(fruits);
//fruits.splice(1, 3);
//fruits.splice(1);
console.log(fruits);
//fruits.splice(1, 1, 'peach', 'watermelon');
console.log(fruits);

// combine two arrays
const fruits2 = ['pear', 'coconut'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

// 5. Searching
// find the index
console.clear();

// indexOf
console.log(fruits);
console.log(fruits.indexOf('apple'));
console.log(fruits.indexOf('peach'));
console.log(fruits.indexOf('coconut'));

// includes
console.log(fruits.includes('strawberry'));
console.log(fruits.includes('coconut'));

// lastIndexOf
console.clear();
fruits.push('apple');
console.log(fruits);
console.log(fruits.indexOf('apple'));
console.log(fruits.lastIndexOf('apple'));

'javascript' 카테고리의 다른 글

[javascript] callback function  (0) 2020.11.18
[javascript] json  (0) 2020.11.17
[javascript] Object  (0) 2020.11.02
[javascript] 클래스와 오브젝트  (0) 2020.10.30
[javascript] 데이터타입  (0) 2020.10.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함