<Java Script> 기초응용 - 삼항연산자, 비구조할당, 단락회로평가, spread 연산자

김고은·2024년 2월 2일

Java_Script

목록 보기
6/7
post-thumbnail

1. 삼항연산자

<script>
let a =3;
a >= 0 ? console.log("양수") : console.log("음수");

const arr = [];
arr.lenth === 0 ? console.log("빈 배열") : console.log("안 빈 배열");

const answer = arr.length === 0?  console.log("빈 배열") : console.log("안 빈 배열");
console.log(answer);

//학점 계산 프로그램
// 90점 이상 a+ 
//50점 이상 b+
//둘 다 아니면 f

let score = 100;
score >= 90? console.log("a+") : score >= 50? console.log("b+"):("f");
</script>

2.단락회로평가

  • && : true & true
  • || : true & false / false & true
<script>

const getName= (person) =>{
    return person && person.name;
};

let person;
const name = getName(person);
console.log(name);



const getName= (person) =>{
    const name =  person && person.name;
    return name || "객체가 아닙니다.";
};

let person = {name : "이정환"};
const name = getName(person);
console.log(name);



const getName= (person) =>{
    const name =  person && person.name; //null
    return name || "객체가 아닙니다.";
};

let person =null;
const name = getName(person);
console.log(name);

</script>

3. 조건문

<script>
function isKoreanFood(food){
  if(['불고기', "비빔밥","떡볶이"].includes(food)){
    return true;
  }
  return false;
}
const food1 = isKoreanFood("불고기");
const food2 = isKoreanFood("파스타");
console.log(food1);
console.log(food2);


const meal = {
  한식 : "불고기",
  중식 : "멘보샤",
  양식 : "파스타",
  일식 : "스테이크"
};


const getMeal = (mealType) => {
  return meal[mealType] || "굶기";
};

console.log(getMeal("중식")); //멘보샤
console.log(getMeal());   //굶기
</script>

4. 비 구조 할당

<script>
// 배열 비구조화
let arr = ["one", "two", "three"];

let [one, two, three] = arr;
console.log(one,two,three);


let [one, two, three] = ["one", "two", "three"];
console.log(one,two,three);

let [one, two, three, four='four'] = ["one", "two", "three"]; //four = 기본값설정 
console.log(one,two,three,four);

let a =10;
let b = 20;
let tmp = 0;

[a,b] = [b,a];
console.log(a,b);


//객체 비구조화
let object = {one : "one", two :"two", three : "three"};

let {one, two, three} = object;
console.log(one, two, three); //key 값으로 접근함


let object = {one : "one", two :"two", three : "three", age : 23};

let {age : Age, one, two, three} = object;
console.log(one, two, three, Age);
</script>

5. spread 연산자

<script>
const cookie = {
  base : "cookie",
  madaIn : "korea"
};

const chocochipCookie = {
  ...cookie,
  toping : "chocochip"
};

const blueberryCookie = {
  ...cookie,
  toping : "blueberry"
};
const strawberryCookie = {
  ...cookie,
  toping : "strawberry"
};

console.log(chocochipCookie);
console.log(blueberryCookie);
console.log(strawberryCookie);




const noTopingCookies = ['촉촉한쿠키', '안촉촉한 쿠키'];
const topingCookie = ["바나나쿠키", "블루베리쿠키", "딸기쿠기","초코칩쿠키"];

const allCookies = [...noTopingCookies,"함정쿠키", ...topingCookie];
console.log(allCookies);

</script>
profile
변화를 즐기는 개발자

0개의 댓글