language/javascript
๋ฐฐ์ด ๊ฐ๋ ๊ณผ APIs
๊ฑด๋ง๋
2021. 11. 25. 22:51
Object
- ์๋ก ์ฐ๊ด๋ ํน์ง๊ณผ ํ๋๋ค์ ๋ฌถ์ด๋๋ ๊ฒ
์๋ฃ๊ตฌ์กฐ
- ๋น์ทํ type์ object๋ค์ ๋ฌถ์ด๋๋ ๊ฒ(dynamically typed language)
- ๋ค๋ฅธ ์ธ์ด์ ๊ฒฝ์ฐ์๋ ๋์ผํ type์ object๋ง์ ๋ฌถ์ ์ ์๋ค.
1. Declaration
const arr1 = new Array();
const arr2 = [1, 2];
2. Index position
const fruits = ['๐', '๐'];
console.log(fruits); // ['๐', '๐']
console.log(fruits.length); // 2
console.log(fruits[0]); // ๐
console.log(fruits[1]); // ๐
console.log(fruits[2]); // undefined
console.log(fruits[fruits.length - 1]); // ๋ฐฐ์ด์ ๋ง์ง๋ง item ์ ๊ทผ, ๐
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 (fruit of fruits) {
console.log(fruit);
}
// c. forEach
// ๋ฐฐ์ด ์์ value๋ค ๋ง๋ค ์ ๋ฌํ ํจ์๋ฅผ ์ถ๋ ฅ
fruits.forEach((fruit) => console.log(fruit));
4. Addition, deletion, copy
// push: add an item to the end
fruits.push('๐', '๐');
console.log(fruits); // ['๐', '๐', '๐', '๐']
// pop: remove an item from the end
fruits.pop(); // ['๐', '๐', '๐']
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(); // ['๐', '๐']
console.log(fruits);
// splice: remove an item by index position
fruits.push('๐', '๐', '๐');
console.log(fruits); // ['๐', '๐', '๐', '๐', '๐']
// splice(์์ index, ์ง์ธ item ๊ฐ์(option))
fruits.splice(1);
console.log(fruits); // ['๐'], ์ง์ ํ index๋ถํฐ ๋ชจ๋ item ์ญ์
fruits.splice(1, 1);
console.log(fruits); // ['๐', '๐', '๐', '๐']
fruits.splice(1, 1, '๐', '๐');
console.log(fruits); // ['๐', '๐', '๐', '๐', '๐']
fruits.splice(1, 0, '๐', '๐'); // item ์ง์ฐ์ง ์๊ณ ํด๋น ์๋ฆฌ์ item ์ฝ์
console.log(fruits); // ['๐', '๐', '๐', '๐', '๐', '๐']
// combine two arrays
const fruits2 = ['๐','๐ฅฅ'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits); // ['๐', '๐', '๐', '๐', '๐', '๐','๐ฅฅ']
- shift, unshift๋ push, pop๋ณด๋ค ํจ์ฌ ๋๋ฆฌ๋ค.
- ๋งจ ์์์ add, remove๊ฐ ์ผ์ด๋๊ธฐ ๋๋ฌธ์ ๊ธฐ์กด์ ์๋ item๋ค์ ์์น๋ฅผ ๊ณ์ํด์ ์ฎ๊ฒจ์ผ ํ๊ธฐ ๋๋ฌธ!
5. Searching
// indexOf: find the index
console.log(fruits); // ['๐', '๐', '๐', '๐', '๐']
console.log(fruits.indexOf('๐')); // 0
console.log(fruits.indexOf('๐')); // 2
console.log(fruits.indexOf('๐ฅฅ')); // -1
// includes
console.log(fruits.includes('๐')); // true
console.log(fruits.includes('๐ฅฅ')); // false
// lastIndexOf
fruits.push('๐');
console.log(fruits); // ['๐', '๐', '๐', '๐', '๐', '๐']
console.log(fruits.indexOf('๐')); // 0
console.log(fruits.lastIndexOf('๐')); // 5
์ฐธ๊ณ
youtube ๋๋ฆผ์ฝ๋ฉ by ์๋ฆฌ
https://www.youtube.com/watch?v=yOdAVDuHUKQ&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=8