개발공부 29일,30일차 [유데미 자바스크립트기본 및 응용 강의]
배열
let arr = [1,"2",true,null,undefined,{},[],(),function(){}]; //배열 리터럴
배열에도 숫자, 문자열 , 함수 등 다 넣을 수 있다.
let arr = [1,2,3,4,5]; //배열 리터럴
console.log(arr[0])//1
console.log(arr[2])//3
console.log(arr[1])//2
배열을 추가하는 방법 및 배열안에 요소 갯수 확인
let arr = [1,2,3,4,5]; //배열 리터럴
arr.push(6);
console.log(arr)
//[1, 2, 3, 4, 5, 6] 가장 마지막에 추가됨.
console.log(arr.length) //6 배열의 갯수
반복문
<for문>
for(let i = 1; i <= 100 ; i++ ){
//반복 수행할 명령
console.log("uri") //uri가 콘솔에 100번찍힘.
}
// let i = 1 초기식
// i <= 100 조건식 100이하일때만 반복수행이됨
// i++ 연산 반복이 한번 수행될때마다 할 연산을 적어줌
// i라는 변수에 값을 1로 지정을 하고 반복문이 한번 수행될 때마다 1씩 증가되어 100이 될때까지
//반복문이 수행이 되게 한다.
배열을 순회하는 방법.
const arr= ["a","b","c"]
for(let i = 0; i < arr.length ; i++ ){
//반복 수행할 명령
console.log(arr[i])
}
//a
//b
//c
//arr배열에 0부터 시작해서 배열의 인덱스갯수만큼 반복한다.
객체를 순회하는 방법
let person = {
name : "유리",
age : 29,
tall : 173
}
const personKeys = Object.keys(person);
//객체에 key값만 뽑아서 배열로 반환시키는 방법
console.log(personKeys)
//['name', 'age', 'tall']
for(let i = 0; i < personKeys.length; i++){
const curKey = personKeys[i];
//person의 key값
const curValue = person[curKey]
//person의 value값
console.log(`${curKey} : ${curValue}`)
}
//name : 유리
//age : 29
//tall : 173
만약 key값이 아닌 values값만 순회하고 싶다면?
let person = {
name : "유리",
age : 29,
tall : 173
}
const personValues = Object.values(person);
//객체에 values값만 뽑아서 배열로 반환시키는 방법
for(let i = 0; i < personValues.length; i++){
console.log(personValues[i])
}
//유리
//29
//173
배열 내장함수
forEach
const arr = [1,2,3,4]
arr.forEach((elm) => console.log(elm*2))
// arr.forEach(function(elm){
// console.log(elm * 2)
// })
//위 반복문과 동일함.
map
배열에 모든요소에 대해서 각각 콜백함수를 수행함.
const arr = [1,2,3,4];
const newArr = arr.map((elm)=>{
return elm * 2
})
console.log(newArr)
// [2, 4, 6, 8]
includes
주어진 배열에서 전달받은 인자와 일치하는지를 확인함.(타입까지 확인함)
불리언식으로 리턴해줌.
const arr = [1,2,3,4];
let number = 3;
console.log(arr.includes(number))
//true
// arr.forEach((elm) => {
// if (elm === number){
// console.log(true)
// //true
// }
// })
indexOf
주어진 배열에서 전달받은 인자와 일치하는 인덱스를 반환하는 함수
일치하지않으면 -1을 반환한다.
const arr = [1,2,3,4];
let number = 3;
console.log(arr.indexOf(number))
// 2
findIndex
객체안에서 찾고자하는 인덱스를 찾을 수 있다.
const arr =[
{color: "red"},
{color: "black"},
{color: "blue"},
{color: "green"},
{color: "blue"},
];
let number = 3;
console.log(arr.findIndex((elm) => elm.color === "blue"))
// 0
다만 배열안에 일치하는 조건이 2개 이상일 경우 제일 위에있는 조건을 찾는다.
find
객체안에서 엘리먼트 자체를 찾을 수 있다.
const arr =[
{color: "red"},
{color: "black"},
{color: "blue"},
{color: "green"},
{color: "blue"},
];
const idx = arr.find((elm) => elm.color === "blue")
console.log(idx)
//{color: 'blue'}
filter
배열을 필터링할 수 있다.
const arr =[
{num:1, color: "red"},
{num:2,color: "black"},
{num:3,color: "blue"},
{num:4,color: "green"},
{num:5,color: "blue"},
];
console.log(arr.filter((elm) => elm.color === "blue"))
//0:{num: 3, color: 'blue'}
//1:{num: 5, color: 'blue'}
slice
배열을 잘라서 원하는 부분만 가지고 올 수 있다.
const arr =[
{num:1, color: "red"},
{num:2,color: "black"},
{num:3,color: "blue"},
{num:4,color: "green"},
{num:5,color: "blue"},
];
console.log(arr.slice(0,2))
//0:{num: 1, color: 'red'}
//1:{num: 2, color: 'black'}
concat
첫번째 명시한 배열뒤에 .concat(두번째 배열)이 붙게 된다.
const arr =[
{num:1, color: "red"},
{num:2,color: "black"},
{num:3,color: "blue"},
];
const arr2 = [
{num:4,color: "green"},
{num:5,color: "blue"},
];
console.log(arr.concat(arr2))
//0:{num: 1, color: 'red'}
// 1:{num: 2, color: 'black'}
// 2:{num: 3, color: 'blue'}
// 3:{num: 4, color: 'green'}
// 4:{num: 5, color: 'blue'}
sort
원본배열에 순서를 사전순으로 정렬한다.
let chars = ['나','다','가'];
chars.sort();
console.log(chars)
// ['가', '나', '다']
숫자를 정렬 하고 싶을땐 sort를 쓰면 사전순이기 때문에 원하는대로 정렬하기 어렵다.
let chars = [60,1,10,3,50,0];
chars.sort();
console.log(chars)
//[0, 1, 10, 3, 50, 60]
조건함수를 줘서 숫자를 오름차순, 내림차순으로 정렬 할 수 있다.
let numbers = [60,1,10,3,50,0];
const compare = (a,b)=>{
//1. 같다
//2. 크다
//3. 작다
if(a>b){
//크다
return 1;
}
if(a<b){
//작다
return -1;
}
//같다
return 0;
}
numbers.sort(compare);
console.log(numbers)
//[0, 1, 3, 10, 50, 60]
a 와 b를 비교해서 a가 크면(1) 앞으로 순서가 뒤로가게되고 작으면(-1)순서가 앞으로 오게된다.
만약 같으면(0) 그자리에 그대로 있는다.
조건함수를 sort에 줘서 원하는 순서로 정렬 할 수 있다.
join
문자열을 하나로 합쳐서 사용 할 수 있다.
const arr = ["유리","님","안녕하세요","또오셨군요"];
console.log(arr.join());
//유리,님,안녕하세요,또오셨군요
console.log(arr.join(" "));
//유리 님 안녕하세요 또오셨군요
console.log(arr.join("메롱"));
//유리메롱님메롱안녕하세요메롱또오셨군요
Truthy & falsy
let a = "";
if(a){
console.log("TRUE")
} else{
console.log("FALSE")
}
//FALSE
조건문에 불리언 조건을 넣지 않아도 true or false값이 출력되는데
true로 나오는건 숫자열, 문자열, 배열 등 이고
false로 출력이 되는건 null, undefined, 0(숫자 0), NaN, 변수에 값을 할당하지 않는경우, “” (문자열 따옴표에 아무것도 넣지 않았을때)
변수가 undefined이거나 값이 null일때는 조건문을 넣어줘야 한다. (아니면 에러가 뜸)
const getName = (person) => {
if(person === undefined || person === null){
return "객체가 아닙니다."
}
return person.name;
};
let person;
let person = null
const name = getName(person);
console.log(name) //객체가 아닙니다.
다만 함수가 많을 경우 조건문을 넣어서 하나하나 해주기가 어렵다.
const getName = (person) => {
if(!person){ //false NOT => true
return "객체가 아닙니다."
}
return person.name;
};
let person;
const name = getName(person);
console.log(name) //유리
!person → person객체가 아니다.
삼항연산자
let a = 3;
a >= 0 ? console.log("양수") : console.log("음수")
// a가 0보다 크면 "양수" : 아니면 "음수"
//아래 조건문이랑 동일하게 적용됨.
// if (a >= 0) {
// console.log("양수");
// } else {
// console.log("음수");
// }
💡물음표 키워드는 앞에가 조건문이다 라는걸 명시함.
let a = [];
a.length === 0 ? console.log("빈 배열") : console.log("안 빈 배열");
//a의 글자수가 0이라면 "빈 배열" : 아니라면 "안 빈 배열"
// if (a.length === 0) {
// console.log("빈 배열");
// } else {
// console.log("안 빈 배열")
// }
let a = [];
const arrayStatus = a.length === 0 ? "빈 배열" : "안 빈 배열";
//a의 글자수가 0이라면 "빈 배열" : 아니라면 "안 빈 배열"을 상수 arrayStatus에 넣음
console.log(arrayStatus) //빈 배열
let a; //undefined
const result = a ? true : false;
console.log(result) //false
let a = [];
const result = a ? true : false;
console.log(result) //true
다만 조건이 2개 이상일 경우 삼항연산자로 하면 가독성이 떨어질 수 있어 웬만하면 if문으로 실행하는게 좋다.
//TODO : 학점 계산 프로그램
//90점 이상 A+
//50점 이상 B+
//둘다 아니면 F
let score = 100;
// score >= 90 ? console.log("A+") : score >= 50 ? console.log("B+") : console.log("F")
if (score >= 90){
console.log("A+")
} else if (score >=50){
console.log("B+")
} else{
console.log("F")
}
단락회로 평가
console.log(false && true)
// 앞이 false이면 값은 무조건 false
console.log(true || false);
// 앞에 true가 오면 무조건 true
console.log(!true)
// 무조건 false
const getName = (person) => {
const name = person && person.name // 유리
//상수 name에 person이고 person.name인값을 넣어준다.
return name || "객체가 아닙니다."
//name이 true이기 때문에 name값이 출력된다.
}
let person = {name : "유리"}
const name = getName(person)
console.log(name) // 유리
조건문 업그레이드
function isKoreaFood(food) {
if (["불고기","떡볶이","비빔밥"].includes(food)) {
return true;
}
return false;
}
const food1 = isKoreaFood("불고기")
const food2 = isKoreaFood("파스타")
console.log(food1) //true
console.log(food2) //false
.includes를 이용해서 배열안에 찾는 파라미터가 있는지 확인해서 있으면 true 없으면false를 출력하게한다.
const getMeal = (mealType)=> {
if(mealType === '한식')return"불고기";
if(mealType === '양식')return"파스타";
if(mealType === '중식')return"멘보샤";
if(mealType === '일식')return"초밥";
return '굶기';
};
console.log(getMeal("한식")); //불고기
console.log(getMeal("양식")); //파스타
console.log(getMeal()); //굶기
⬇️객체에 괄호 표기법을 통해서 호출함.
const meal = {
한식: "불고기",
중식: "멘보샤",
일식: "초밥",
양식: "스테이크",
인도식: "카레",
}
const getMeal = (mealType) => {
return meal[mealType] || "굶기"
}
console.log(getMeal("한식"))
console.log(getMeal())
getMeal함수를 호출할때 mealType의“한식”이라는 값을 전달했기 때문에 meal이라는 객체에서 “한식”의 값을 가져오게된다.
비 구조화 할당(배열과 객체를 우아하게 사용하는 방법)
let arr = ["one", "two", "three"];
let [a, b, c] = arr;
console.log(a, b, c)
//one two three
아래코드랑 동일한 코드
let [a, b, c] = ["one", "two", "three"];
console.log(a, b, c)
//one two three
let [a, b, c, d] = ["one", "two", "three"];
console.log(a, b, c, d)
//one two three undefined
배열없는 요소를 할당받고자 하면 undefined의 값을 가지게된다.
let [a, b, c, d = "d"] = ["one", "two", "three"];
console.log(a, b, c, d)
//one two three d
할당받지 못했던 변수에 = “할당할값“을 적용해주면 기본값으로 할당받는다.
비구조 할당으로 swap하기
let a = 10;
let b = 20;
[a, b] = [b, a]
console.log(a, b)
// 20 10
let object = {
one: "one",
two: "two",
three: "three",
name: "uri"
}
let { name: myName, one, two, three, abc = 'four' } = object
console.log(one, two, three, myName, abc)
//one two three uri four
비 구조화 할당은 순서가 아니라 키값을 기준으로 비구조화 할당이 이루어지기 때문에 변수가 앞에있어도 순서그대로 출력된다.
만약 키값을 변경해주고 싶으면 키값 : 변수명을 넣어서 변경 할 수 있다.
진짜 .. 자바스크립트를 한사람이 만들었다고하는데 정말 천재인가..?어떻게 이걸? 로봇이 아닐까?