자바스크립트에서 구조화하기

안녕하세요 데브스입니다.

이 기사에서 우리는 JavaScript의 구조화를 배울 것입니다

목차


  • Array Destructuring in JavaScript
  • Additional use of Array Destructuring
  • Assigning default values using destructuring assignment
  • Destructuing of nested array
  • Object Destructuring in JavaScript
  • Nested object destructuring
  • Combined Array and Object Destructuring

  • 시간을 낭비하지 않고 들어가 보자.

    구조 분해 할당 구문은 배열의 값이나 객체의 속성을 고유한 변수로 압축 해제할 수 있는 JavaScript 표현식입니다.

    그러나 왜 우리는 구조 분해가 필요합니까?
    먼저 배열 요소와 개체 속성에 액세스하는 전통적인 방법을 살펴보겠습니다.

    let arr = [1,2,3,4]
    arr[2] //3
    
    let obj = {
       fname: 'john',
       lname: 'doe'
    }
    obj.fname //john
    //or
    obj["fname"] //john
    


    배열이나 개체가 중첩되어 있을 때 요소나 속성에 액세스하는 것을 생각해 보십시오. 약간 복잡합니다.

    이제 우리는 Destructuring 개념을 사용하여 일이 더 간단하고 쉬워지는 방법을 볼 것입니다.

    구조 분해 할당은 다음과 같습니다.

    «패턴» = «값»

    1. 어레이 구조화:

    syntax:

    [a,b,c] = some_array
    

    Example:

    let arr = ["John", "Doe"]
    
    // older way
    let firstName = arr[0]
    let lastName = arr[1]
    console.log(firstName, lastName); //John Doe
    
    //array destructuring way
    let [firstName, lastName] = arr;
    console.log(firstName, lastName); //John Doe
    
    //what if there are more values in array
    var [fname,lname] = ['john', 'doe', 'capscode', 26, car]
    
    //we can use rest operator,
    var [fname,lname, ...others] = ['john', 'doe', 'capscode', 26, car]
    

    2. Destructuring의 추가 사용

    //Works with any iterables of JavaScript
    String iterable
    let [a, b, c] = "abc"; 
    console.log(a) // "a"
    console.log(b) // "b"
    console.log(c) // "c"
    
    let [first, ...rest] = "Hello";
    console.log(first) // "H"
    console.log(rest) // ["e", "l", "l", "o"]
    
    //Swap variables trick using array destructuring
    let guest = "Jane";
    let admin = "Pete";
    
    // Swap values: make guest=Pete, admin=Jane
    [guest, admin] = [admin, guest];
    

    3. Destructuring 할당을 사용하여 기본값을 할당할 수도 있습니다.

    let [firstName, surname] = [];
    alert(firstName); // undefined
    alert(surname); // undefined
    
    so to get out of this,
    // default values
    let [name = "Guest", surname = "Anonymous"] = ["Julius"];
    alert(name);    // Julius (from array)
    alert(surname); // Anonymous (default used)
    
    

    4. 중첩 배열의 구조화

    const person = ['John', ["capscode", "google", "yahoo"], 'Doe'];
    const [fname, [comp1, comp2, comp3]] = person;
    console.log(comp3) //"yahoo"
    

    5. 객체 구조화

    Syntax:

    let {var1, var2} = {var1:, var2:}
    

    Example:

    let person={
        fname: "John",
        lname: "Doe",
        company: "capscode"
    }
    
    let {fname,lname,company } = person;
    
    //we can also use rest operator
    let {fname,...others} = person;
    console.log(others)
    console.log(others.lname)
    console.log(others.company)
    

    what if we will use Destructuing assignment without declaration?

    let fname, lname, company;
    
    {fname, lname, company} = {
         fname: "John",
         lname: "Doe",
         company: "capscode"
    }; 
    // error in this line
    

    The problem is that JavaScript treats {.....} in the main code flow (not inside another expression) as a code block.

    The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

    {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

    // okay now
    ({fname, lname, company} = {
         fname: "John",
         lname: "Doe",
         company: "capscode"
    })
    

    🔥NOTE: 🔥Your (....) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.
    I will tell why I am saying like this,
    just take a look at the below 2 examples carefully,

    let href, pathname
    ({href} = window.location)
    ({pathname} = window.location)
    //TypeError: (intermediate value)(intermediate value) is not a function
    
    let href
    somefunc()
    ({href} = window.location)
    //TypeError: somefunc(...) is not a function
    

    🔥 What's happening is, Without the semicolon, when parsing, Javascript engine considers both lines as a single call expression.
    🔥 So if you are using () after any () then put ; after first () 😅

    6.중첩된 객체 구조 분해

    const student = {
        name: 'John Doe',
        age: 16,
        scores: {
            maths: 74,
            english: 63
        }
    };
    
    // We define 3 local variables: name, maths, science
    const { name, scores: {maths, science = 50} } = student;
    console.log(maths)//74
    console.log(english)//undefined
    

    7. 결합된 배열 및 객체 구조화

    Example,

    const props = [
      { id: 1, name: 'John'},
      { id: 2, name: 'Saam'},
      { id: 3, name: 'Rahul'}
    ];
    
    const [,, { name }] = props;
    
    console.log(name); // "Rahul"
    

    Destructuring values that are not an object, array, or iterable gives you a TypeError

    let [NaN_] = NaN //TypeError: NaN is not iterable
    let [Boolean_] = true // TypeError: true is not iterable
    let [Number_] = 10 = TypeError: 10 is not iterable
    let [NULL_] = nul //TypeError: null is not iterable
    let [undefined_] = undefined //TypeError: undefined is not iterable
    
    // NOTE: String are iterable in JavaScript
    let [String_] = "CapsCode" // "C"
    

    Thank you for reading this far. This is a brief introduction of Destructuring Assignment in JavaScript .
    If you find this article useful, like and share this article. Someone could find it useful too. If you find anything technically inaccurate please feel free to comment below.

    Hope its a nice and informative read for you.
    VISIT
    https://www.capscode.in/#/blog 더 알아보려면...
    다음 블로그 기사에서 뵙겠습니다. 조심해!!

    감사,

    좋은 웹페이지 즐겨찾기