ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

2์ฐจ์› ๋ฐฐ์—ด in JavaScirpt

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์ž์ฒด์—๋Š” 2์ฐจ์› ๋ฐฐ์—ด์ด ์—†๋‹ค. 

๋”ฐ๋ผ์„œ const arr = [][] ์ฒ˜๋Ÿผ ํ•œ ๋ฒˆ์— 2์ฐจ์› ๋ฐฐ์—ด์„ ์„ ์–ธํ•  ์ˆ˜ ์—†๋‹ค.

ํ•˜์ง€๋งŒ, ํ…Œํฌ๋‹‰์„ ์ด์šฉํ•ด 2์ฐจ์› ๋ฐฐ์—ด๊ณผ ๋น„์Šทํ•œ ๋ฐฐ์—ด์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

 

 

1๏ธโƒฃ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋นˆ 2์ฐจ์› ๋ฐฐ์—ด ์ƒ์„ฑ 

const board = new Array(n);
for(let i=0; i < n; i++){
	board[i] = new Array(n);
}

 

 

2๏ธโƒฃ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ง์ ‘ ๊ฐ’์„ ํ• ๋‹นํ•ด ๋ฐฐ์—ด ์ƒ์„ฑ 

board = [];
for(let i=0; i < n; i++){
	board[i] = []
	for(let j=0; j < n; j++){
		board[i][j] = '.';
	}
}

 

3๏ธโƒฃ Array.from() ๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•ด 2์ฐจ์› ๋ฐฐ์—ด ์ƒ์„ฑ (ES6+)

// arr[4][4] ๋นˆ ๋ฐฐ์—ด ์ƒ์„ฑ
const arr = Array.from(Array(4), () => new Array(4))

// arr[4][2]์„ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ ๋ฐฐ์—ด ์ƒ์„ฑ
const arr = Array.from(Array(4), () => new Array(2).fill(0)

 

Array.from() ์ฐธ๊ณ 

Array.from() ๋ฉ”์„œ๋“œ๋Š” ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด(array-like object)๋‚˜ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด(iteralbe object)๋ฅผ

shallow copye(์–•์€ ๋ณต์‚ฌ)ํ•ด ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค.

์ฒซ๋ฒˆ์งธ ์ธ์ž๋กœ ์–•๊ฒŒ ๋ณต์‚ฌํ•  ๊ฐ์ฒด๋ฅผ ์ „๋‹ฌํ•˜๊ณ , ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ์— ๋Œ€ํ•ด ํ˜ธ์ถœํ•  Mapping ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌํ•œ๋‹ค.

Array.from(arrayLike[, mapFn[, thisArg]])
Array.from('foo');
// expected output: Array ["f", "o", "o"]

Array.from([1, 2, 3], x => x + x);
// expected output: Array [2, 4, 6]

 

728x90
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
ยซ   2025/01   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ
250x250