ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JS 100์ œ] ๋ฌธ์ œ27 - ๊ฐ์ฒด ๋งŒ๋“ค๊ธฐ
    ๐Ÿ›  develop/CodingTest 2022. 12. 5. 09:42

    ๋ฌธ์ œ

    ์ฒซ๋ฒˆ์งธ ์ž…๋ ฅ์—์„œ๋Š” ํ•™์ƒ์˜ ์ด๋ฆ„์ด ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ž…๋ ฅ๋˜๊ณ , ๋‘๋ฒˆ์งธ์—๋Š” ๊ทธ ํ•™์ƒ์˜ ์ˆ˜ํ•™ ์ ์ˆ˜๊ฐ€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๋‘ ๊ฐœ๋ฅผ ํ•ฉ์ณ ํ•™์ƒ์˜ ์ด๋ฆ„์ด key์ด๊ณ  value๊ฐ€ ์ˆ˜ํ•™ ์ ์ˆ˜์ธ ๊ฐ์ฒด๋ฅผ ์ถœ๋ ฅํ•ด์ฃผ์„ธ์š”.

    ์ž…๋ ฅ
    Yujin Hyewon
    70 100
    
    ์ถœ๋ ฅ
    { 'Yujin': 70, 'Hyewon': 100 }

     

    ๋‚˜์˜ ํ’€์ด

    const key = prompt("์ด๋ฆ„์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”").split(" ");
    const value = prompt("์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”").split(" ");
    let res = {};
    
    for (let i = 0; i < key.length; i++) {
      res[key[i]] = value[i];
    }
    
    console.log(res);
    • key ๊ฐ’ ์ฆ‰, ์ด๋ฆ„์„ ๋ฐ›์„ ๋ณ€์ˆ˜์™€ value ๊ฐ’, ์ ์ˆ˜๋ฅผ ๋ฐ›์„ ๋ณ€์ˆ˜๋ฅผ ๋ฐ›์•„์ค€ ๋’ค split ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฐฐ์—ด๋กœ ๋„ฃ์–ด์ค€๋‹ค.
    • for ๋ฌธ์„ ์ด์šฉํ•˜์—ฌ ๋ฐ›์€ key ๊ฐ’ ๊ฐœ์ˆ˜ ๋งŒํผ for ๋ฌธ์„ ๋Œ๋ ค์ฃผ๋ฉด์„œ, res ๊ฐ์ฒด์— key value ์Œ ์ฆ‰ ํ”„๋กœํผํ‹ฐ๋ฅผ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค. 
    • key value ์˜ ๊ฐ’์€ ๋ฐฐ์—ด๋กœ ๋‹ด๊ฒจ์žˆ๊ธฐ ๋•Œ๋ฌธ์— i ๋ฅผ ์ด์šฉํ•˜์—ฌ key[i] value[i] ํ˜•ํƒœ๋กœ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜์—ฌ ์ˆœ์„œ๋Œ€๋กœ ์Œ์„ ์ถ”๊ฐ€์‹œ์ผœ์ฃผ์—ˆ๋‹ค.

     

    ์ •๋‹ต

    const keys = prompt('์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”').split(' ');
    const values = prompt('์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”').split(' ');
    const obj = {};
    
    for (let i=0; i<keys.length; i++) {
      obj[keys[i]] = parseInt(values[i], 10);
    }
    
    console.log(obj);
    • ์ •๋‹ต๋„ ๋กœ์ง์€ ๋™์ผํ•˜๋‚˜ parseInt ๋ฅผ ์ƒ๋žตํ•œ ๊ฒƒ์„ ๋ฐœ๊ฒฌํ–ˆ๋‹ค... ์ ์ˆ˜๋Š” ์ˆซ์ž์˜€๋Š”๋ฐ, parseInt ๋ฅผ ๋นผ๋‹ค๋‹ˆ... ๋‹ค์Œ๋ถ€ํ„ฐ๋Š” ์ฃผ์˜ํ•ด์•ผ๊ฒ ๋‹ค.

     

    JS ๊ฐ„๋‹จ ๋ณต์Šต

    ๊ฐ์ฒด ์ƒ์„ฑ

    var player = {
    	name: "Son",
    	number: 7,
    	age: 30
    };

     

    ๊ฐ์ฒด ์ ‘๊ทผ

    console.log(player.name); // "son"
    console.log(player['age']); // 30

     

     

    ๊ฐ์ฒด ์ถ”๊ฐ€

    // ๊ฐ์ฒด.์ƒ์„ฑํ• key์ด๋ฆ„ = value;
    
    player.score = 23;
    player["score"] = 23;

     

    ๊ฐ์ฒด ์ˆ˜์ •

    // ๊ฐ์ฒด.์ˆ˜์ •ํ• key๊ฐ’ = ์ˆ˜์ •ํ•  ์ƒˆ๋กœ์šด value๊ฐ’
    
    player.age = 31; 
    player["age"] = 31;

     

    ๊ฐ์ฒด ์‚ญ์ œ

    delete player.age;
    
    console.log(player.age); // undefined

    ๋Œ“๊ธ€