아래 그림과 같이 input tag에 댓글을 달면 로그인 시 사용한 이메일 정보(sessionStorage)와 댓글이 입력되는 웹페이지를 구현한다고 했을 때, login.html에서 수집한 이메일 정보를 review.html에서 사용하기 위해서는 이메일 정보가 지속성 있게 유지될 필요가 있다.
review.html 페이지login.html 페이지
sessionStorage 객체를 이용하면 이를 손쉽게 구현할 수 있다.
login.html과 연동된 login.js에 아래와 같은 코드를 입력하고,
// login.js
let id = document.getElementById("emailInput");
// 이메일정보가 입력되는 input tag의 id(혹은 class)를 불러온다.
sessionStorage.setItem("ID", id.value);
// sessionStorage에 해당 정보의 값을 저장한다.
댓글이 작성될 review.html과 연동된 review.js에 아래와 같은 코드를 입력한다. 이 후에 해당 값을 원하는 대로 사용하면 끝!
// review.js
let yourID = sessionStorage.getItem("ID");
// sessionStorage에 저장된 이메일 정보 값을 review.js에서 불러온다.
개발자 도구에서 살펴보면 아래 그림과같이 Application 탭의 Session Storage에 해당 값이 저장되어 있는 것을 확인할 수 있다.
// Q1. make a string out of an array
{
const fruits = ["apple", "banana", "orange"];
// di it yourself!
// console.log(fruits.toString()); // .join과 .toString의 차이는 구분자(seperator)
// answer
const result = fruits.join(" and ");
console.log(result);
}
// Q2. make an array out of a string
{
const fruits = "🍎, 🥝, 🍌, 🍒";
// do it yourself!
// const fruit = fruits.split(",");
// console.log(fruit);
// answer
const fruit = fruits.split(",");
console.log(fruit);
}
// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
const array = [1, 2, 3, 4, 5];
// do it yourself!
// const reverseArray = array.reverse();
// console.log(reverseArray);
// answer
const reverseArray = array.reverse();
console.log(reverseArray);
console.log(array); // 원래 배열도 바뀐다.
}
// Q4. make new array without the first two elements
{
const array = [1, 2, 3, 4, 5];
// do it yourself!
// const result = array.slice(2);
// const resultNew = array.slice(2, 5);
// console.log(result);
// console.log(resultNew);
// // answer
const result = array.slice(2, 5);
console.log(result);
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
{
// do it yourself!
// for (let i = 0; i < students.length; i++) {
// if (students[i].score === 90) {
// console.log(students[i]);
// }
// }
// answer
// const result = students.find(function (value) {
// return value.score === 90;
// });
const result = students.find((value) => value.score === 90);
console.log(result);
}
// Q6. make an array of enrolled students
{
// do it yourself!
// const result = students.filter((value) => value.enrolled === true);
// console.log(result);
// // answer
const result = students.filter((student) => student.enrolled === true);
console.log(result);
}
// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
// do it yourself!
// let result = [];
// for (let i = 0; i < students.length; i++) {
// result.push(students[i].score);
// }
// console.log(result);
// answer
const result = students.map((student) => student.score);
console.log(result);
}
// Q8. check if there is a student with the score lower than 50
{
// do it yourself!
// const result = students.some((student) => student.score < 50);
// console.log(result);
// answer
const result = students.some((student) => student.score < 50);
console.log(result);
const result2 = !students.every((student) => student.score >= 50);
console.log(result2);
}
// Q9. compute students' average score
{
//do it yourself!
// let result = 0;
// for (let i = 0; i < students.length; i++) {
// result += students[i].score;
// }
// console.log(result / 5);
// answer
// const result = students.reduce((prev, curr) => {
// console.log("----------");
// console.log(prev);
// console.log(curr);
// return prev + curr.score;
// }, 0);
const result = students.reduce((prev, curr) => prev + curr.score, 0);
console.log(result / students.length);
}
// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
// do it yourself!
// const result = students.map((student) => student.score);
// const resultArray = result.join();
// console.log(resultArray);
// answer
const result = students
.map((student) => student.score)
// .filter((score) => score >= 50)
.join();
console.log(result);
}
// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
{
// do it yourself!
// const result = students
// .map((student) => student.score)
// .sort((a, b) => a - b)
// .join();
// console.log(result);
// answer
const result = students
.map((student) => student.score)
.sort((a, b) => a - b)
.join();
console.log(result);
}
8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리 | 프론트엔드 개발자 입문편 (JavaScript ES6 )
"use strict";
// Array
// 1. Declaration
const arr1 = new Array();
const arr2 = [];
// 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]);
console.clear();
// 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. for each
// fruits.forEach(function (fruit, index) {
// console.log(fruit, index);
// });
// fruits.forEach((fruit, index) => {
// console.log(fruit, index);
// });
// fruits.forEach((fruit, index) => console.log(fruit, index));
fruits.forEach((fruit) => console.log(fruit));
// 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();
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, 1);
console.log(fruits);
fruits.splice(1, 1, "greenapple", "watermelon");
// fruits.splice(1, 0, "greenapple", "watermelon");
console.log(fruits);
// combine two arrays
const fruits2 = ["coconut", "durian"];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);
// 5. Searching
// indexOf: find the index
console.clear();
console.log(fruits);
console.log(fruits.indexOf("apple"));
console.log(fruits.indexOf("lemon"));
console.log(fruits.indexOf("durian")); // 찾는 값이 없을 경우 -1을 출력
// includes
console.log(fruits.includes("durian"));
console.log(fruits.includes("peach"));
// lastIndexOf
console.clear();
fruits.push("apple");
console.log(fruits);
console.log(fruits.indexOf("apple")); // 첫번째 값의 index만 출력
console.log(fruits.lastIndexOf("apple")); // 마지막 값의 index만 출력
object[key]는 변수로 접근하지만, object.key 및 object['key']는 object(객체)의 property(key)에 접근한다.
example 1
let num = {
one: 1,
two: 2,
};
let one = "two";
console.log(num.one); // result: 1 --> num object에서 one이라는 key의 value 값을 출력한다.
console.log(num["one"]); // result: 1 --> num object에서 one이라는 key의 value 값을 출력한다.
console.log(num[one]); // result: 2 --> one이라는 변수에는 num object의 two라는 key 값이 할당되었기 때문에(??뭔지 좀 이해가 안간다..) num object에서 two라는 key의 value 값을 출력한다.
example 2
const user = { name: "Steve", age: 4 };
function printValue(obj, key) {
// console.log(obj.key); undefined --> user라는 object에는 'key'라는 key값이 없기 때문에 발생
// console.log(obj["key"]); undefined --> 위와 동일
console.log(obj[key]); // ['key']가 아니라 [key]를 사용 했다. 변수로 접근. 즉, 아래 printValue의 "name"과 "age"에 해당하는 key의 value 값을 출력한다.
}
printValue(user, "name"); // result: Steve
printValue(user, "age"); // result: 4
크롬 브라우저의 개발자 도구에서 아래와 같이 코드를 작성하면 조금 특이한 결과 값(?)이 나온다.
개발자 도구에서의 console 창은 어떤 명령에 대한 "결과 값"을 표시해주는 역할을 하는데 printNew 변수를 선언한 문장(const printNew)은 그 자체로는 아무런 결과 값을 보여주지 않기 때문에 undefined(첫번째 빨간 상자)가 출력된다. 두 번째 빨간 상자의 undefined도 console.log() 문장에 대한 동일한 결과라고 볼 수 있다.
그렇다면 초록색 상자는 무슨 의미일까?
초록색 상자의 undefined는 printNew 변수에 할당된 함수의 결과 값중 하나로 봐야 하는 것인가?? 함수가 실행되면 먼저 "print"가 출력되고, 이후에는 console.log("print"); 구문 자체에 대한 결과값으로 "undefined"가 출력된 것으로 이해를 해야 하는건지 궁금하다.