자바스크립트

 

 

 

인프런 수강하기 ==>   자바스크립트 중급 강좌

 

초급자를 위해 준비한
[프로그래밍 언어] 강의입니다.

이 수업은 중급 자바스크립트 수업으로, "자바스크립트 기초 지식이 있으신 분"을 대상으로 진행합니다.

 

강의 목록  :  https://www.youtube.com/playlist?list=PLZKTXPmaJk8JZ2NAC538UzhY_UNqMdZB4

 

 

 

 

 

1 .변수, 호이스팅, TDZ(Temporal Dead Zone)

 

 

  • 자바스크립트의 스코프는 함수 레벨 스코프를 따른다.
  • 같은 함수 레벨에 존재하면 값을 참조할 수 있다는 건데
  • ES6에서 let 키워드가 도입되면서 블록 레벨 스코프를 사용할 수 있게 됐다.

 

전역 스코프

- 어디서든 참조 가능

전역 변수

- 전역 스코프를 갖는 전역 변수

- 어디서든 참조 가능

 

지역 스코프

- 함수 자신과 하위 함수에서만 참조 가능

지역 변수

- 지역 스코프를 갖는 지역 변수

- 함수 내에서 선언된 변수로 해당 함수와 해당 함수의 하위 함수에서 참조 가능

 

암묵적 전역 변수

- 선언하지 않은 변수에 값을 할당하면 전역 객체의 프로퍼티가 되어 전역 변수처럼 동작한다.

- 하지만 변수 선언이 없었기 때문에 호이스팅은 발생하지 않는다.

(variable = 1) === (window.variable = 1)

//////////////////////////////////////

console.log('test', test);

function temp () {
  test = 10;
};

temp(); // test is not defined

 

참조  : https://bbangaro.tistory.com/62

 

호이스팅 예

let age=30;

function showAge(){  
  console.log(age);
  let age=50;
}

showAge();
Uncaught ReferenceError: Cannot access 'age' before initialization 

 

 

 

 

2 .생성자 함수

 

 

생성자 함수(constructor function)와 일반 함수에 기술적인 차이는 없습니다. 다만 생성자 함수는 아래 두 관례를 따릅니다.

  1. 함수 이름의 첫 글자는 대문자로 시작합니다.
  2. 반드시 'new' 연산자를 붙여 실행합니다.

예시:

function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user = new User("보라");

alert(user.name); // 보라
alert(user.isAdmin); // false

 

new User(...)를 써서 함수를 실행하면 아래와 같은 알고리즘이 동작합니다.

  1. 빈 객체를 만들어 this에 할당합니다.
  2. 함수 본문을 실행합니다. this에 새로운 프로퍼티를 추가해 this를 수정합니다.
  3. this를 반환합니다.

예시를 이용해 new User(...)가 실행되면 무슨 일이 일어나는지 살펴 보도록 하겠습니다.

 

 

function User(name) {
  // this = {};  (빈 객체가 암시적으로 만들어짐)

  // 새로운 프로퍼티를 this에 추가함
  this.name = name;
  this.isAdmin = false;

  // return this;  (this가 암시적으로 반환됨)
}

 

이제 let user = new User("보라")는 아래 코드를 입력한 것과 동일하게 동작합니다.

let user = {
  name: "보라",
  isAdmin: false
};

 

 

function Item(title, price){
    //this={};
    this.title=title;
    this.price=price;
    this.showPrice=function(){
        console.log(`가격은 ${price} 원 입니다.`);
    }
    //return this;
}

const item1 =new Item("인형", 3000);
const item2 =new Item("가방", 4000);
const item3 =new Item("지갑", 9000);

console.log(item1,item2, item3);

item3.showPrice();

출력:

Item {title: '인형', price: 3000, showPrice: ƒ} Item {title: '가방', price: 4000, showPrice: ƒ} Item {title: '지갑', price: 9000, showPrice: ƒ}

가격은 9000 원 입니다.

 

출처  : https://ko.javascript.info/constructor-new

 

 

 

 

 

3 .객체 메소드(Object methods), 계산된 프로퍼티(Computed property)

 

chapter_03

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3 .객체 메소드(Object methods), 계산된 프로퍼티(Computed property)</title>
</head>
<body>
<script>
let n ="name";
let a ="age";

const user ={
    [n]:"Mike",
    [a]:30,
    //[1+4]:5
};
console.log(user);
//출력
//{5: 5, name: 'Mike', age: 30}

function makeObj(key, val){
    return {
        [key] :val
    }
}

const obj =makeObj("나이", 33);
console.log(obj);
//{나이: 33}



//**** 객체 복사 : Object.assign   ******
const user2=user;
const user3 =Object.assign({}, user);
console.log("객체 복사 Object.assign  : " , user3);
console.log("얕은복사 :",user2===user, "깊은 복사 :",  user3===user);
//객체 복사 Object.assign  :  {name: 'Mike', age: 30}
//얕은복사 : true 깊은 복사 : false



//******객체 키값만 반환: Object.keys *********
const result =Object.keys(user);
console.log(result);
//['name', 'age']


//******객체 값만 반환: Object.keys *********
const valueResult =Object.values(user);
console.log(valueResult);
//['Mike', 30]




//******객체 키와 값 반환: Object.entries *********
//Object.entries 객체를 배열로 반환처리
const keyValueResult=Object.entries(user);
console.log(keyValueResult);

// [Array(2), Array(2)]
// ['name', 'Mike']
// ['age', 30]
// length: 2

console.log(keyValueResult[0]);
// ['name', 'Mike']

// 배열을 객체로 변환 처리
//**** Object.fromEntries() 는 Object.entries() 의 역을 수행
let arr =[
    ["mon","월"],
    ["tue","화"]
]
const resultArr=Object.fromEntries(arr);
console.log(" resultArr  : ",resultArr);
//resultArr  :  {mon: '월', tue: '화'}
</script>
</body>
</html>

 

 

 

 

 

 

4 .심볼(Symbol)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Symbol</title>
</head>
<body>
<script>
const a =Symbol(); //new 를 붙이지 않습니다.
const b =Symbol();

console.log("a==b", a==b);
console.log("a===b", a===b);
//a==b false
//a===b false


//Symbol :유일성 보장
const id =Symbol("id");

//유일성이 보장되므로 객체의 키로 사용한다.
//property key :심볼형


//Symbol.for() :전역 심볼
//하나의 심볼만 보장받을 수 있음
//없으면 만들고, 있으면 가져오기 때문
//Symbol 함수는 매번 다른 Symbol 값을 생성하지만,
//Symbol.for 메소드는 하나를 생성한 뒤 키를 통해 같은 Symbol을 공유

const id1=Symbol.for("id");
const id2=Symbol.for("id");
console.log("id1===id2 :", id1===id2);
//id1===id2 true

//Symbol.keyFor 는   Symbol.for의  키값을 알려줌.
Symbol.keyFor(id1); 
console.log("Symbol.keyFor(id1) :", Symbol.keyFor(id1));
//Symbol.keyFor(id1) : id




//Symbol 은   description 으로 이름을 알수 있다.
const id3 =Symbol("id 입니다.");
id3.description; 
console.log("id3.description:", id3.description);
//id3.description: id 입니다.



//** 숨겨진 Symbole key 보는 법
const id7 =Symbol('id7');
const user={
    name:"Mike",
    age:30,
    [id7]:'myid'
}
//숨겨진 심볼 key 만 출력
Object.getOwnPropertySymbols(user);
console.log("Object.getOwnPropertySymbols(user):", Object.getOwnPropertySymbols(user));
//Object.getOwnPropertySymbols(user): [Symbol(id7)]

//전체 출력
Reflect.ownKeys(user);
console.log("Reflect.ownKeys(user):", Reflect.ownKeys(user));
//Reflect.ownKeys(user): (3) ['name', 'age', Symbol(id7)]


</script>    
</body>
</html>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Symbol test</title>
</head>
<body>
<script>
//다른 개발자가 만들어 놓은 객체
const user={
    name:"Mike",
    age:30
}  



//내가 작업
//user.showName=function(){};
const showName=Symbol("show name");
user[showName]=function(){
    console.log("user[showName] 심볼 :", this.name);
}


user[showName]();
//user[showName] 심볼 : Mike


//사용자가 접속해서 보는 메세지
for(let key in user){
    console.log(`His ${key}  is  ${user[key]} `);
}
// His name  is  Mike 
// His age  is  30 



</script>    
</body>
</html>

 

 

 

 

 

 

5 .숫자, 수학 메소드(Number, Math)

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>숫자, 수학 메소드(Number, Math)</title>
</head>
<body>
<script>
let num1=5.1;
let num2=5.7;

console.log("Math.ceil(num1) : ", Math.ceil(num1));
console.log("Math.ceil(num2) : ", Math.ceil(num2));
// Math.ceil(num1) :  6
// Math.ceil(num2) :  6

console.log("Math.floor(num1) : ", Math.floor(num1));
console.log("Math.floor(num2) : ", Math.floor(num2));
// Math.floor(num1) :  5
// Math.floor(num2) :  5

console.log("Math.round(num1) : ", Math.round(num1));
console.log("Math.round(num2) : ", Math.round(num2));
// Math.round(num1) :  5
// Math.round(num2) :  6


//numObj.toFixed([소수 부분의 자릿수]);
let numObj = 1.23456 

console.log(numObj.toFixed()); // 결과: '1'
console.log(numObj.toFixed(6)); // 결과: '1.234560'
console.log(numObj.toFixed(3)); // 결과: '1.235'
console.log(numObj.toFixed(1)); // 결과: '1.2'

numObj = 0.0005678 
console.log(numObj.toFixed()); // 결과: '0'
console.log(numObj.toFixed(5)); // 결과: '0.00057'
console.log(numObj.toFixed(3)); // 결과: '0.001'
console.log(numObj.toFixed(1)); // 결과: '0.0'

numObj = 12345.67 
//console.log(numObj.toFixed(101)); // 결과: '오류'
//파라 매터가 0과 100 사이의 값이 아니라면 Uncaught RangeError: toFixed() digits argument must be between 0 and 100라는 오류가 발생



// isNaN() / 매개변수가 숫자인지 검사하는 함수
// 123.123은 숫자이므로 false를 반환합니다.
// '123.123'은 따옴표로 감쌌지만, 숫자로 취급하여 false를 반환합니다.
// 'Not a Number'는 숫자가 아니므로 true를 반환합니다.
// 123*123은 숫자이므로 false를 반환합니다.
// '123*123'은 따옴표 안에 문자가 있으므로 숫자가 아닌 것으로 취급하여 true를 반환합니다.




//parseInt()  
//parseInt 는 숫자로 시작된 부부까지만 읽고 문자가 나오면 숫자만 반환, 문자로 시작되는 것은 읽지 못함
let margin="100px";
console.log("parseInt(margin) : ",parseInt(margin));
console.log("Number(margin) : ",Number(margin));
//parseInt(margin) :  10
//Number(margin) :  NaN


let redColor= 'f3';
console.log("parseInt(redColor) : ",parseInt(redColor)); 
//parseInt(redColor) :  NaN


//parseInt 로  16진수 변환 방법
let redColor2= 'f3';
console.log("parseInt(redColor2,16) : ",parseInt(redColor2,16)); 
//parseInt(redColor2,16) :  243

console.log("parseInt('11',2) : ",parseInt('11',2)); 
//parseInt('11',2) :  3

//******** parseFloat() ****//
let padding ='18.5%';
console.log("parseInt(padding) : ",parseInt(padding)); 
//parseInt(padding) :  18

console.log("parseFloat(padding) : ",parseFloat(padding)); 
//parseFloat(padding) :  18.5


//******* Math.random();
//1~100 사이 임의의 숫자를 뽑고 싶다면?
Math.floor(Math.random()*100)+1


//Math.max() ; Math.min();
Math.max(1,4,-1,5,10,9,5.54);  //10
Math.min(1,4,-1,5,10,9,5.54);   //-1

//Math.abs();  //절대값
Math.abs(-1); //1

//Math.pow(n,m);//제곱

//Math.sqrt()//제곱근
console.log("Math.sqrt() : " , Math.sqrt(16));
//Math.sqrt() :  4


</script>
</body>
</html>

 

 

 

 

 

 

 

 

6.문자열 메소드(String methods)

 

String 메소드는 String 객체에 정의된 문자열과 관련된 작업을 할 때 사용하는 메소드입니다.

 

1. String.fromCharCode()

2. String.fromCodePoint()

String.fromCharCode() 메소드

이 메소드는 쉼표로 구분되는 일련의 유니코드에 해당하는 문자들로 구성된 문자열을 반환합니다.

예제

String.fromCharCode(65, 66, 67); // "ABC"

String.fromCodePoint() 메소드

이 메소드는 쉼표로 구분되는 일련의 코드 포인트(code point)에 해당하는 문자들로 구성된 문자열을 반환합니다.

예제

String.fromCodePoint(65, 66, 67); // "ABC"

String.fromCodePoint(0x2F804);    // "\uD87E\uDC04"

String.fromCodePoint(194564);     // "\uD87E\uDC04"

 

문자열에서의 위치 찾기

다음 메소드는 String 인스턴스에서 특정 문자나 문자열이 처음으로 등장하는 위치나 마지막으로 등장하는 위치를 반환합니다.

 

- indexOf()

- lastIndexOf()

 

이 메소드들은 문자열을 찾기 시작할 String 인스턴스의 위치를 두 번째 인수로 전달할 수 있습니다.

만약 전달받은 특정 문자나 문자열을 찾을 수 없을 때는 -1을 반환합니다.

 

예제

var str = "abcDEFabc";

str.indexOf('abc');     // 0  -> 자바스크립트에서 인덱스는 0부터 시작함.

str.indexOf('abcd');    // -1 -> 문자열을 비교할 때 문자의 대소문자를 구분함.

str.indexOf('abc', 3);  // 6  -> 인덱스 3부터 'abc'를 찾기 시작함.

str.lastIndexOf('abc'); // 6

str.lastIndexOf('d');   // -1

str.lastIndexOf('c');   // 8

 

substr 함수로 문자열 자르는 방법

var str = '자바스크립트';

var result1 = str.substr(0, 2);
// 결과 : "자바"

var result2 = str.substr(2, 4);
// 결과 : "스크립트"

var result3 = str.substr(2);
// 결과 : "스크립트"

 

substr("시작 위치", "길이") 또는 substr("시작 위치")

substr() 함수는 시작 위치부터 해당 길이만큼 문자열을 자르는 아주 기본적인 함수이다. "길이" 부분을 생략하면 시작 위치부터 문자열 끝까지 자른다.

 

 

 

substring 함수로 문자열 자르는 방법

var str = '자바스크립트';

var result1 = str.substring(0, 2);
// 결과 : "자바"

var result2 = str.substring(2, 5);
// 결과 : "스크립"

var result3 = str.substring(2, 6);
// 결과 : "스크립트"

var result4 = str.substring(2);
// 결과 : "스크립트"

 

substring("시작 위치", "종료 위치") 또는 substring("시작 위치")

substring() 함수는 시작 위치에서 종료 위치까지 문자열을 자른다. 주의할 점은 종료 위치의 -1까지 문자열을 자른다는 것이다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문자열 메소드(String methods)</title>
</head>
<body>
<script>
let list=[
    "01. 들어가며",
    "02. JS의 역사",
    "03. 자료형",
    "04. 함수",
    "05. 배열"
]    
let newList =[];
for(let i=0; i<list.length; i++){
    newList.push(list[i].slice(4));
}
console.log("newList : ",newList);
//newList :  (5) ['들어가며', 'JS의 역사', '자료형', '함수', '배열']



//금칙어 :콜라
function hasCola(str){
    console.log(str.indexOf('콜라'));
    if(str.indexOf('콜라')){        
        console.log("금칙어가 있습니다.");
    }else{
        console.log("통과");
    }
}

hasCola("와 사이다가 짱이야!"); //-1
hasCola("무슨소리, 콜라가  최고"); //6
hasCola("콜라"); //0
//결과 오류=>
// 금칙어가 있습니다.
// 금칙어가 있습니다.
// 통과



//===>첫번째 단어에서 존재할 경우 0 따라서, >-1 클경우
function hasCola2(str){
    if(str.indexOf('콜라')>-1){
        console.log("금칙어가 있습니다.");
    }else{
        console.log("통과");
    }
}

hasCola2("와 사이다가 짱이야!"); //-1
hasCola2("무슨소리, 콜라가  최고"); //6
hasCola2("콜라"); //0
// 통과
// 금칙어가 있습니다.
// 금칙어가 있습니다.


//**********************
//***  includes()  문자가 존재 여부만 확인
function hasCola3(str){
     console.log("str.includes('콜라')" ,str.includes('콜라'));
    if(str.includes('콜라')){
        console.log("금칙어가 있습니다.");
    }else{
        console.log("통과");
    }
}
hasCola3("와 사이다가 짱이야!"); //
hasCola3("무슨소리, 콜라가  최고"); //
hasCola3("콜라"); //
// str.includes('콜라') false
// 통과
// str.includes('콜라') true
// 금칙어가 있습니다.
// str.includes('콜라') true
// 금칙어가 있습니다.

</script>    
</body>
</html>

 

 

 

 

 

 

 

7.배열 메소드1(Array methods)

 

 

 slice()

slice는 배열의 인자로 받는 "시작index"부터 "끝index"까지 자른 복사본을 리턴 한다.

특징 : 원본의 배열 값은 바뀌지 않는다.

 

구문

arr.slice([시작값],[끝값])

 

 

 

splice()

const fruits = ['수박', '바나나', '망고', '두리안'];
const removed = fruits.splice(2, 0, '딸기', '사과');
console.log(fruits);
// ['수박', '바나나', '딸기', '사과', '망고', '두리안'];
console.log(removed);

 

 

forEach()

///****   forEach  
const myArr = ["가", "나", "다", "라", "마"];
myArr.forEach((currentElement, index, array) => {
    console.log(`요소: ${currentElement}`  , `index: ${index}`,  array);    
});
// 요소: 가 index: 0 (5) ['가', '나', '다', '라', '마']
// 요소: 나 index: 1 (5) ['가', '나', '다', '라', '마']
// 요소: 다 index: 2 (5) ['가', '나', '다', '라', '마']
// 요소: 라 index: 3 (5) ['가', '나', '다', '라', '마']
// 요소: 마 index: 4 (5) ['가', '나', '다', '라', '마']

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 메소드1(Array methods)</title>
</head>
<body>
<script>
const fruits = ['수박', '바나나', '망고', '두리안'];
const removed = fruits.splice(2, 0, '딸기', '사과');
console.log(fruits);
// ['수박', '바나나', '딸기', '사과', '망고', '두리안'];
console.log(removed);


///****   forEach  
const myArr = ["가", "나", "다", "라", "마"];
myArr.forEach((currentElement, index, array) => {
    console.log(`요소: ${currentElement}`  , `index: ${index}`,  array);    
});
// 요소: 가 index: 0 (5) ['가', '나', '다', '라', '마']
// 요소: 나 index: 1 (5) ['가', '나', '다', '라', '마']
// 요소: 다 index: 2 (5) ['가', '나', '다', '라', '마']
// 요소: 라 index: 3 (5) ['가', '나', '다', '라', '마']
// 요소: 마 index: 4 (5) ['가', '나', '다', '라', '마']



let arr=["Mike","Tom","Jane"];
arr.forEach((name, index)=>{
    console.log(`index(${index}) , name :${name}`);
})
// index(0) , name :Mike
// index(1) , name :Tom
// index(2) , name :Jane



//find true 이면 멈추고 반환처리한다.
let arr2 =[1,2,3,4,5,6];
const result=arr2.find((item)=>{
    return item %2 ===0;
});
console.log("find result :", result);
//find result : 2


let userList=[
    {name:"Mike",age:30},
    {name:"Jane",age:27},
    {name:"Tom",age:10},
]
const result2=userList.find((user)=>{
    if(user.age>19){
        return true;
    }
    return false;  
});

console.log("find result2 :", result2);
//find result2 : {name: 'Mike', age: 30}


//********  findIndex  인덱스값 반환
const result3=userList.findIndex((user)=>{
    if(user.age>19){
        return true;
    }
    return false;  
});

console.log("findIndex result3 :", result3);
//findIndex result3 : 0



//** arr.filter(fn);
//만족하는 모든 요소를 배열로 반환


//map  가공해서 값 반환
let newUserList =userList.map((user, index)=>{
    return Object.assign({}, user, 
        {
            isAdult:user.age>19
        }
    );
})
console.log("map newUserList : ", newUserList);
// {name: 'Mike', age: 30, isAdult: true}
// {name: 'Jane', age: 27, isAdult: true}
// {name: 'Tom', age: 10, isAdult: false}


/// join 공백이면  , 콤마 삽입
let arr3=["안녕", "나는", "철수야!"];
let result4 =arr.join("-");
console.log("join result4 :" ,result4);
//join result4  : Mike-Tom-Jane


</script>    
</body>
</html>

 

 

 

 

 

 

 

8.배열 메소드2 (sort, reduce)

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배열 메소드2 (sort, reduce)</title>
</head>
<body>
<script>

/******************************
arr.sort()
배열 재정렬
주의! 배열 자체가 변경됨
인수로 정렬 로직을 담은 함수를 받음 
**********************************/

let arr =[1,5,4,2,3];
arr.sort();
console.log(arr);
//(5) [1, 2, 3, 4, 5]



let arr2 =[27,8,5,13];
arr2.sort();
console.log(arr2);
//sort() 는 숫자가 아니라 문자열 인식하여 다음과 같이 출력
//(4) [13, 27, 5, 8]


//sort() 비교 함수처리를 해야 한다. (method) Array<number>.sort(compareFn?: (a: number, b: number) => number): number[]
function fn(a, b){
    return a-b;
}
arr2.sort(fn);
const result=arr2.sort((a, b)=>{
    console.log(a, b);
    return a-b;
})
console.log("sort arr2 : ", arr2);
//(4) [5, 8, 13, 27]
console.log("sort result ",result);


//정렬 라이브러리 Lodash 사용
//_.sortBy(arr);
//https://lodash.com/



/******************************
arr.reduce()
인수로 함수를 받음
(누적 계산값, 현재값) =>{return 계산값};
**********************************/
//배열의 모든수 합치기
let arr3 =[1,2,3,4,5];
//for, for of, forEach

let result1 =0;
arr3.forEach((num)=>{
    result1  +=num;
})
console.log("배열의 모든수 합치기 result1 : forEach ",result1);
//배열의 모든수 합치기 result1 : forEach  15


const result2=arr3.reduce( (acc,curr)=>{
    return acc+curr;
}, 0)
console.log("reduce  배열의 모든수 합치기: ",result2);
//reduce  배열의 모든수 합치기:  15

let userList=[
    {name:"Mike",age:30},
    {name:"Tom",age:10},
    {name:"Jane",age:27},
    {name:"Sue",age:26},
    {name:"Harry",age:43},
    {name:"Steve",age:60},
]

let result3=userList.reduce((acc, curr)=>{
        if(curr.age >30){
           acc.push(curr.name) ;
        }
        return acc;
}, []);
//초기값이 빈배열 누적처리
console.log("reduce 30 살보다 많은 사람: ",result3);
//reduce 30 살보다 많은 사람:  (2) ['Harry', 'Steve']


let result4=userList.reduce((acc, curr)=>{       
        return acc+curr.age;
}, 0);
console.log("reduce 나이  누적처리: ",result4);
//reduce 나이  누적처리:  196

</script>    
</body>
</html>

 

 

 

 

 

 

 

 

 

9.구조 분해 할당 (Destructuring assignment)

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>구조 분해 할당 (Destructuring assignment)</title>
</head>
<body>
<script>
//배열 구조 분해
let users =['Mike', 'Tom', "Jane"];
let [user1, user2, user3]=users;
console.log(user1, user2, user3);
//Mike Tom Jane

let str="Mike-Tom-Jane";
let [a, b, c]=str.split("-");
console.log("split :" ,str.split("-"));
console.log("split abc :" ,a, b, c);
//split : (3) ['Mike', 'Tom', 'Jane']
//split a, b, c : Mike Tom Jane


</script>    
</body>
</html>

 

 

 

객체(object)에서의 구조 분해 할당

객체에서의 구조 분해 할당은 아주아주 많이 쓰이는 문법입니다. 객체 내부의 프로퍼티 값을 간편하게 분해해서 변수에 저장할 수 있게 해 줍니다.

배열에서의 구조 분해 할당과 쓰이는 의미는 동일하되, 쓰이는 대상이 객체로 바뀐 것 뿐입니다.

단, 분해되는 대상이 배열은 array의 value(element) 였다면, 객체는 분해되는 대상이 객체의 property 인 차이가 있습니다.

 

onst obj = {
  name: "John",
  age: 18,
  memo: "Hello",
};
const { name, age, memo } = obj;
console.log(name); // "John"
console.log(age); // 18
console.log(memo); // "Hello"

// 만약 구조 분해 할당을 사용하지 않는다면?
// 아래와 같이 직접 대입해 주어야 한다.
const name = obj.name;
const age = obj.age;
const memo = obj.memo;

 

 

 

 

 

 

10.나머지 매개변수, 전개 구문(Rest parameters, Spread syntax)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>나머지 매개변수, 전개 구문(Rest parameters, Spread syntax)</title>
</head>
<body>
<script>
    //arguments
/************************
1)함수로 넘어온 모든 인수에 접근
2)함수내에서 이용 가능한 지역 변수
3)length/index
4)Array 형태의 객체
5)배열의 내장 메서드 없음
6)(forEach, map)
************************/



//나머지 매개별수 (Rest parameters)
/**********************************
*나머지 매개변수
*전달 받은 모든 수를 더해야 함
**********************************/
/**
function add(...numbers){
    let result=0;
    numbers.forEach((num)=> (result +=num));
    return result;
}
**/
function add(...numbers){
    return numbers.reduce((acc, curr)=> acc+curr);    
}
console.log("1~3 :" ,add(1,2,3));
console.log("1~10 : ",add(1,2,3,4,5,6,7,8,9,10));
// 1~3 : 6
// 1~10 :  55




/***************************************
*나머지 매개변수 항상 마지막
*user 객체를 만들어 주는 생성자 함수
****************************************/
function User(name, age, ...skills){
    this.name=name;
    this.age=age;
    this.skills=skills
}

const user1=new User('Mike', 30,'html', 'css');
const user2 =new User('Tom', 20,'js','React');
const user3 =new User('Jane', 10,'Engiish');

console.log("user1 :", user1);
console.log("user2 :", user2);
console.log("user3 :", user3);




//전개 구문 (Spread syntax ) :배열
let arr1=[1,2,3];
let arr2=[4,5,6];
let result=[0, ...arr1, ...arr2, 7,8,9];


//전개 구문(Spread syntax) :복제
let arr3 =[1,2,3];
let arr4=[...arr3 ,4];
console.log("전개 구문 arr4 : ", arr4);
//전개 구문 arr4 :  (4) [1, 2, 3, 4]




/************************************
 * 전개 구문
 * arr5 을 [4,5,6,1,2,3] 으로
 * 
*************************************/

let arr5=[1,2,3];
let arr6=[4,5,6];


// arr6.reverse().forEach((num)=>arr5.unshift(num));
// console.log("arr5 : ", arr5);
//arr5 :  (6) [6, 5, 4, 1, 2, 3]

arr5=[...arr6, ...arr5];
console.log("전개 구문 연산 arr5 : ", arr5);
//전개 구문 연산 arr5 :  (6) [4, 5, 6, 1, 2, 3]


let user ={name:"Mike"};
let info ={age:30};
let fe =["JS", "React"];
let lang =["korean", "English"];

// user =Object.assign({}, user, info, {
//     skills :[]
// });

// fe.forEach((item)=>{user.skills.push(item)});
// lang.forEach((item)=>{user.skills.push(item)});
// console.log("user : " , user);


user ={
    ...user, 
    ...info,
    skills:[
        ...fe,
        ...lang
    ]
};
console.log("user : " , user);


</script>
</body>
</html>

 

 

 

 

 

 

 

소스 :  https://github.com/braverokmc79/Intermediate-javaScript-1

 

 

 

 

about author

PHRASE

Level 60  라이트

은(殷) 나라 탕왕(湯王)이 하(夏) 나라 걸왕(桀王)을 멸망시키고 주(周) 나라 무왕이 은 나라 주왕(紂王)을 멸망시켰다. 이들 혁명은 모두 하늘의 뜻에 순종하고 백성의 민심에 호응해서 이루어진 것이다. -역경

댓글 ( 4)

댓글 남기기

작성