๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
study/js

JavaScript Array ์ •๋ฆฌ! (feat. ๋“œ๋ฆผ์ฝ”๋”ฉ ์•จ๋ฆฌ๋‹˜)

by stilinski 2022. 1. 10.
728x90
'use strict';

/* Array ๐Ÿ•

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

// 2. Index postion
const fruits = ['๐ŸŽ','๐ŸŒ'];
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

// 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 (api)
fruits.forEach(function(fruit, index, array) {
    console.log(fruit, index, array);
})

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


//4. Addtion, deletion, copy
//add an item to the end
fruits.push('๐Ÿ', '๐Ÿ');
console.log(fruits);

//pop: remove an item from the end
fruits.pop();
console.log(fruits);


//unshift : add an item to the beginning
fruits.unshift('๐Ÿ', '๐Ÿ');
console.log(fruits);

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


//note!! shift, unshift are slower than pop, push ์ „์ฒด์ ์ธ ๋ฐ์ดํ„ฐ๊ฐ€ ์›€์ง์—ฌ์•ผํ•จ
//splice : remove an item by index postion
fruits.push('๐Ÿ‰', '๐Ÿ‹', '๐Ÿ');
console.log(fruits);
fruits.splice(1, 1, '๐Ÿ’'); // index ํ•˜๋‚˜๋งŒ ์“ฐ๋ฉด ๊ทธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ๋’ค๊นŒ์ง€ ์ „๋ถ€ ์‚ญ์ œ
// fruits.splice(1, 0, '๐Ÿ’'); ์‚ญ์ œ ์•ˆํ•˜๊ณ  ๋„ฃ๊ธฐ๋งŒ๋„ ๊ฐ€๋Šฅ
console.log(fruits);

//cimbine two arryas
const fruits2 = ['๐Ÿ‡','๐Ÿฅ‘'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

// 5. Searching
// indexOf: find the index
console.clear();
console.log(fruits);
console.log(fruits.indexOf('๐Ÿ‰'));
console.log(fruits.indexOf('๐Ÿฅ‘')); // -1

// includes
console.log(fruits.includes('๐Ÿ‰'));
console.log(fruits.includes('๐Ÿฅ‘'));

//lastIndexOf  ๊ฐ™์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ์„ ๋•Œ
fruits.push('๐Ÿ‰');
console.log(fruits);
console.log(fruits.indexOf('๐Ÿ‰'));
console.log(fruits.lastIndexOf('๐Ÿ‰'));



์ด๋ฒˆ ํŽธ์€ ๋‹จ์ˆœํ–ˆ๋‹ค~

๊ทธ๋Ÿฐ๋ฐ ์ด๋Ÿฐ ๊ฒƒ๋“ค์ด ์–ด๋””์— ์–ด๋–จ ๋•Œ ์“ฐ์ด๋Š” ๊ฑด์ง€ ๋ชฐ๋ผ์„œ ์กฐ๊ธˆ ๋‹ต๋‹ตํ•˜๊ธฐ๋„ ํ•˜๊ณ  ๋จธ๋ฆฌ์— ๋” ์ž˜ ์•ˆ ๋“ค์–ด์˜จ๋‹ค!

๊ทธ๋ž˜๋„ ์ด๋Ÿฐ ๊ฒƒ๋„ ๋‹ค ํ•„์š”ํ•œ ๊ณผ์ •์ด๋ผ๊ณ  ์ƒ๊ฐํ•œ๋‹ค.

๋นจ๋ฆฌ ๊ธฐ์ดˆ์ ์ธ ๊ฑฐ ๋‹ค ๋ฐฐ์šฐ๊ณ  ์‹ค์ „์— ๋Œ์ž…ํ•˜๊ณ  ์‹ถ๋‹ค~!~

 

728x90

๋Œ“๊ธ€