Mi Lugarcito

JavaScript - Array ๊ธฐ์ดˆ ๋ณธ๋ฌธ

JavaScript

JavaScript - Array ๊ธฐ์ดˆ

selene park 2021. 3. 28. 02:45
'use strict';

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

//2. Index position 
const fruits = ['๐Ÿ', '๐ŸŒ'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);
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);
}

//c. forEach & ์ด๋ฆ„์ด ์—†๋Š” ํ•จ์ˆ˜๋Š” ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ์‚ฌ์šฉํ•œ๋‹ค. (ํ•œ์ค„๋งŒ ์žˆ๋Š” ๊ฒฝ์šฐ๋Š” {} ์‚ญ์ œ ๊ฐ€๋Šฅํ•จ)
fruits.forEach((fruit)=> console.log(fruit));

//๋ฐฐ์—ด์— Addtion, delete, copy
// push : add an item to the end
fruits.push('๐Ÿ‘','๐Ÿ‡');
console.log(fruits);

// pop : remove an item from the end
fruits.pop();
console.log(fruits);//์•„์ดํ…œ ํ•œ๊ฐœ ๋น ์ง 

// ์•ž์—์„œ๋ถ€ํ„ฐ ์•„์ดํ…œ ๋„ฃ๊ธฐ : add an item to the beginning (unshift)
fruits.unshift('๐Ÿ…','๐Ÿฅ');
console.log(fruits);
// ์•ž์—์„œ๋ถ€ํ„ฐ ์•„์ดํ…œ ๋นผ๊ธฐ : remove an item from the beginning (shitf)
fruits.shift();
console.log(fruits);

//note !! : shift, unshift are slower than pop, push
//splice : remove an item by index position
fruits.push('๐Ÿบ','๐Ÿ','๐Ÿ‹');
console.log(fruits);
fruits.splice(1,2);
console.log(fruits);
fruits.splice(1,1,'๐Ÿ˜€','โ›ช๏ธ');//์‚ญ์ œ  ๋ฐ ์ถ”๊ฐ€๋„ ๊ฐ€๋Šฅ
console.log(fruits);

//concat : combine tow arrays
const fruits2 = ['โŒš๏ธ','โ™ค'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

//5. Searching (indexOf, includes)
//find the index -->  ๋ฐฐ์—ด์•ˆ์— ํ•ด๋‹น๊ฐ’์ด ์—†์„๊ฒฝ์šฐ ? -1 ์ถœ๋ ฅํ•œ๋‹ค.
console.clear();
console.log(fruits);
console.log(fruits.indexOf('๐Ÿฅ'));
console.log(fruits.includes('๐Ÿ…'));//f or t ๋กœ ๋ฐ˜ํ™˜


//lastIndexOf
console.clear();
fruits.push('๐Ÿ…');
console.log(fruits.indexOf('๐Ÿ…'));
console.log(fruits.lastIndexOf('๐Ÿ…'));