๐Ÿฆœ Computer Language/JavaScript

[JavaScript] ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น ๊ทธ๋ฆฌ๊ณ  SWAP

๋ฐฐ์—ด์˜ ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น

๋ฐฐ์—ด์—์„œ ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น์„ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, ๋ฐฐ์—ด ์•ˆ์— ์žˆ๋Š” ๊ฐ’์„ ์ถ”์ถœํ•ด์„œ ๋ณ€์ˆ˜ / ์ƒ์ˆ˜๋กœ ๋ฐ”๋กœ ์„ ์–ธ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

๋ฐฐ์—ด ์•ˆ์— ์žˆ๋Š” ์›์†Œ๋ฅผ ์ƒˆ๋กœ ์„ ์–ธํ•ด์ฃผ๊ณ  ์‹ถ์„ ๋•Œ ๊ต‰์žฅํžˆ ์œ ์šฉํ•œ ๋ฌธ๋ฒ•์ด๋‹ค. 

 

# Case 1: ๊ธฐ์กด ํ• ๋‹น ๋ฐฉ๋ฒ•

let colors = ["red", "green", "blue"];

let color0 = colors[0];
let color1 = colors[1];
let color2 = colors[2];

console.log(color0, color1, color2); // red green blue

# Case 2: ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น

let [color1, color2, color3] = ["red", "green", "blue"];

console.log(color0, color1, color2); // red green blue

Case 1๊ณผ 2 ๋ชจ๋‘ ๊ฐ™์€ ๊ฒฐ๊ณผ๋ฅผ ๋‚˜ํƒ€๋‚ด์ง€๋งŒ ๋‘ ๋ฒˆ์งธ ์ฝ”๋“œ๊ฐ€ ํ›จ์”ฌ ๊ฐ„๋‹จํ•œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

์ด๋ ‡๊ฒŒ ๋Œ€๊ด„ํ˜ธ๋ฅผ ์ด์šฉํ•ด์„œ ๋ฐฐ์—ด์˜ ๊ฐ’์„ ์ˆœ์„œ๋Œ€๋กœ ํ• ๋‹น๋ฐ›์•„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š” ๊ฒƒ์„ ๋ฐฐ์—ด์˜ ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น์ด๋ผ๊ณ  ํ•œ๋‹ค.

 

๋งŒ์•ฝ ํ• ๋‹นํ•  ๋ณ€์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ’๋ณด๋‹ค ์ ๋‹ค๋ฉด ํ• ๋‹น๋˜์ง€ ๋ชปํ•œ ๋ณ€์ˆ˜์—๋Š” ๋‹น์—ฐํ•˜๊ฒŒ๋„ undefined๊ฐ€ ํ• ๋‹น๋œ๋‹ค.

let [color0, color2, color3, color4] = ["red", "green","blue"];

console.log(color0, color2, color3, color4); // red green blue undefined

์ด๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•ด ๊ธฐ๋ณธ๊ฐ’์„ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

let [color0, color2, color3, color4 = "yellow"] = ["red", "green","blue"];

console.log(color0, color2, color3, color4); // red green blue yellow

 

๊ฐ์ฒด์˜ ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น

๊ฐ์ฒด์—์„œ ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น์„ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, ๊ฐ์ฒด ์•ˆ์— ์žˆ๋Š” ๊ฐ’์„ ์ถ”์ถœํ•ด์„œ ๋ณ€์ˆ˜ / ์ƒ์ˆ˜๋กœ ๋ฐ”๋กœ ์„ ์–ธ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

 

# Case 1: ๊ธฐ์กด ํ• ๋‹น ๋ฐฉ๋ฒ•

let person = {
	name: "Jedi",
    age: 20,
    phonenumber: 01012345678,
};

let name = person.name;
let age = person.age;
let phonenumber: person.phonenumber;

 

# Case 2: ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น

let person = {
	name: "Jedi",
    age: 20,
    phonenumber: 01012345678,
};

let { name, age, phonenumber } = person;

์ด๋ ‡๊ฒŒ ๊ฐ์ฒด์—์„œ๋Š” Key๊ฐ’๊ณผ ๋ณ€์ˆ˜๋ช…๋งŒ ์ผ์น˜์‹œํ‚ค๋ฉด ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋งŒ์•ฝ ๋‹ค๋ฅธ ๋ณ€์ˆ˜ ๋ช…์„ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ':'๋ฅผ ์ด์šฉํ•˜๋ฉด ๋œ๋‹ค.

let person = {
	name: "Jedi",
    age: 20,
    phonenumber: 01012345678,
};

let { name, age, phonenumber: number } = person;

console.log(number); // 01012345678

์œ— ์˜ˆ์‹œ์ฒ˜๋Ÿผ phonenumber ๋Œ€์‹  number ๋ผ๋Š” ๋ณ€์ˆ˜ ๋ช…์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

SWAP

๋ณดํ†ต ๊ฐ ๋ณ€์ˆ˜์˜ ๊ฐ’์„ ์„œ๋กœ ๋ฐ”๊พธ๊ธฐ ์œ„ํ•ด์„œ ๊ฐ’์„ ๋‹ด์•„ ๊ตํ™˜ํ•ด์ค„ ๋ณ€์ˆ˜(temp)๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

let a = 10;
let b = 20;

let temp = a;

a = b;
b = temp;

console.log(a, b); // 20 10

 

ํ•˜์ง€๋งŒ, ๋น„๊ตฌ์กฐํ™”ํ• ๋‹น์„ ํ™œ์šฉํ•˜๋ฉด temp ์—†์ด๋„ ์‰ฝ๊ฒŒ ๊ฐ’์„ swap ํ•  ์ˆ˜ ์žˆ๋‹ค.

let a = 10;
let b = 20;

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