0. Declaration, index position
배열의 포인트는 인덱스
const arr1 = new Array();
const arr2 = [1, 2];
const fruits = ['a', 'b'];
console.log(fruits);
console.log(fruits.length);
1. Looping over an array
// 1. for
for (let i=0; i<fruits.length; i++) {
console.log(fruits[i]);
}
// 2. for of
for (let fruit of fruits) {
console.log(fruit);
}
// 3. forEach
fruits.forEach((fruit) => console.log(fruit));
2. Addition, deletion, copy
// push : add an item to the end
fruits.push('c',"d");
console.log(fruits);
// pop : remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits);
// unshift : add and item to the beginning
fruits.unshift('c');
console.log(fruits);
// shift : remove and item from the beginning
fruits.shift();
console.log(fruits);
// splice : remove and item by index position
fruits.push('x', 'y', 'z');
console.log(fruits);
fruits.splice(1, 1); // 원하는 인덱스 범위 지정
console.log(fruits);
// concat : combine two arrays
const fruits2 = ['☆', '★'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);
+ Note!! shift, unshift are slower then pop, push!!
3. Searching
//find the index
console.log(newFruits.indexOf("★"));
console.log(newFruits.includes("★"));
//lastIndexOf
newFruits.push('a');
console.log(newFruits);
console.log(newFruits.indexOf('a'));
console.log(newFruits.lastIndexOf('a'));
+ Quiz
// Q1. make a string out of an array
{
const fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits){
console.log(fruit);
}
// answer
const answer = fruits.join();
console.log(answer);
}
// Q2. make an array out of a string
// split : Split a string into substrings using the specified separator and return them as an array.
{
const fruits = '🍎, 🥝, 🍌, 🍒';
const fruitArray = ['🍎', '🥝', '🍌', '🍒'];
console.log(fruitArray);
// answer
const answer = fruits.split(", ");
console.log(answer);
}
// Q3. make this array look like this: [5, 4, 3, 2, 1]
// 배열 자체를 reverse -> array 입력시 reversedarray 호출
{
const array = [1, 2, 3, 4, 5];
const reversedArray = array.reverse();
console.log(reversedArray);
}
// Q4. make new array without the first two elements
// splice : Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
// slice : Returns a copy of a section of an array.
{
const array = [1, 2, 3, 4, 5];
/* const notAnswer = array.splice(0, 2); // 완전 삭제
console.log(notAnswer); */
const answer = array.slice(2, 5); // 삭제 아님
console.log(answer);
console.log(array);
}
class Student {
constructor(name, age, enrolled, score) {
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score = score;
}
}
const students = [
new Student('A', 29, true, 45),
new Student('B', 28, false, 80),
new Student('C', 30, true, 90),
new Student('D', 40, false, 66),
new Student('E', 18, true, 88),
];
// Q5. find a student with the score 90
// find : Returns the value of the first element in the array where predicate is true, and undefined
{
const result1 = students.find ((student) => student.score === 90);
console.log(result1);
}
// Q6. make an array of enrolled students
// filter : Returns the elements of an array that meet the condition specified in a callback function.
{
const result2 = students.filter ((student) => student.enrolled);
console.log(result2);
}
// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
// map : Calls a defined callback function on each element of an array, and returns an array that contains the results.
{
const result3 = students.map ((student) => student.score);
console.log(result3);
}
// Q8. check if there is a student with the score lower than 50
// some : Determines whether the specified callback function returns true for any element of an array.
// every : Determines whether all the members of an array satisfy the specified test.
{
const result = students.find ((student) => student.score < 50);
console.log(result); // 누구냐고 물어보면 -> A
const result4 = students.some((student) => student.score < 50);
console.log(result4); // True
const result5 = !students.every((student) => student.score >= 50);
console.log(result5); // True
}
// Q9. compute students' average score
// reduce : Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
// -> 값 누적시 사용함
{
const selectedScore = students.map ((student) => student.score);
console.log(selectedScore);
const averageScore = (selectedScore[0]+selectedScore[1]+selectedScore[2]+selectedScore[3]+selectedScore[4])/5
console.log(averageScore);
//answer
const result6 = students.reduce((prev, curr) => prev+curr.score, 0);
console.log(result6/students.length);
}
// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
// join : Adds all the elements of an array separated by the specified separator string.
{
const selectedScore = students.map ((student) => student.score).join();
console.log(selectedScore);
}
// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
// sort : Sorts an array in place. This method mutates the array and returns a reference to the same array.
{
const selectedScore = students.map ((student) => student.score)
.sort()
.join();
console.log(selectedScore);
}
'Programming > JavaScript' 카테고리의 다른 글
정규 표현식을 외워보자 (0) | 2024.04.28 |
---|---|
flex-shrink, flex-wrap, justify-content (0) | 2024.03.14 |
JS 문법 정리 (5) (0) | 2023.08.22 |
JS 문법 정리 (4) (0) | 2023.08.18 |
JS 문법 정리 (3) (1) | 2023.08.15 |