728x90

Q. 입력받은 n(숫자)만큼의 층을 생성하는 피라미드를 출력하라.
(단, n은 양수이며, 각 층의 양측 공백은 space로 채워야한다)

--- Examples
pyramid(1)
    '#'
pyramid(2)
    ' # '
    '###'
pyramid(3)
    '  #  '
    ' ### '
    '#####'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/39b671ce6e2d2c0ebf93828114a9336cfb66bf8e/exercises/pyramid/index.js

😢 각 층(level)의 column은 홀수로 출력되어야 하며, 가운데(midpoint)를 찾아 확장하는 것이 핵심이다.
이 두 가지 핵심 포인트를 찾는 것에 시간이 조금 걸렸다.

 

1, 3, 5, 7, 9 ...처럼 홀수로만 반복되는 것을 발견할 수 있다.

😊 Solution 1)
먼저, 해당 피라미드의 가운데지점(midpoint)을 세팅해준다. (2*n-1)
외부 for loop의 row(행)은 각 층수이기 때문에 받은 숫자(n)만큼 반복되고,
내부 for loop의 column(열)은 항상 홀수로 출력되어야 하기 때문에 2*n-1만큼 반복되어야 한다.
그리고 만약 각 층의 #이 채워질 범위가 midpoint - row <= column <= midpoint + row에 해당하면 #,
그게 아니라면 ' '(space)를 level에 대입해준다. 그리고 내부 for loop이 끝날 때마다 각 층을 출력해준다.

Solution 2) 재귀함수
먼저, 함수의 parameter에 row=0, level=''default로 설정해준다. 초기화 후 다른 값으로 반복 대입이 필요하기 때문이다.
Base Case 1)로 만약 row(행)가 n(받은 입력값)과 같으면 return;하여 작업을 끝내주고,
Base Case 2)만약 각 층의 값이 level.length(2*n-1)만큼 채워지면 다음 row(층) 작업(재귀)을 실행시켜주고,
원래 하던 작업은 return; 시켜준다.(중요)(Solution 1의 column을 여기서는 level로 대체해준다)
만약 return해주지 않으면, 아래로 작업이 진행되기 때문에 의도하지 않는 실행이 발생될 수 있기 때문이다.
그 후 Solution 1)과 마찬가지로 midpoint - row <= level.length <= midpoint + row 범위에 해당하면 #,
그게 아니라면 ' '을 level에 대입하여준다.
그리고 각 층의 level.length만큼 반복시켜주기 위해 pyramid(n, row, level + add)로 각 층을 재귀함수로 반복시켜준다.

✔ default

function pyramid(n, row=0, level='') 좌측의 row와 level은 입력받지 않는 이상 default인 0과 ''로 실행된다.

https://babeljs.io/docs/en/learn/#default-rest-spread

 

Babel · The compiler for next generation JavaScript

The compiler for next generation JavaScript

babeljs.io

Full Code

function pyramid(n, row = 0, level = '') {
if (row === n) {
return;
}
 
if (level.length === 2 * n - 1) {
console.log(level);
return pyramid(n, row + 1);
}
 
const midpoint = Math.floor((2 * n - 1) / 2);
let add;
if (midpoint - row <= level.length && midpoint + row >= level.length) {
add = '#';
} else {
add = ' ';
}
 
pyramid(n, row, level + add);
}
 
// function pyramid(n) {
// const midpoint = Math.floor((2 * n - 1) / 2);
 
// for (let row = 0; row < n; row++) {
// let level = '';
 
// for (let column = 0; column < 2 * n - 1; column++) {
// if (midpoint - row <= column && midpoint + row >= column) {
// level += '#';
// } else {
// level += ' ';
// }
// }
 
// console.log(level);
// }
// }

 

728x90

https://www.acmicpc.net/problem/11654

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/2c58f2ea15236b75873c5f215996968ebc3c42e3

😢 학부에서 C나 Java를 쓸 때는 자주 사용했던 ASCII Code인데, JavaScript를 주로 사용하게되면서 오랜만에 써보았다.
아니 JavaScript에서는 처음 ASCII Code를 다뤘다.

😊 C나 Java에서는 변환명세 %d, %c 등을 통해 다뤘던 기억이 나는데,
JavaScript에서는 String.charCodeAt(index) helper method를 사용하면 된다.
그리고 4번째 줄에서 trim()도 사용하였지만, 사실 이 문제에서는 굳이 사용하지 않아도 된다.
다른 정답자들도 모두 이 방법으로 풀었다. 다른 방법이 딱히 없나보다.

✔ String.charCodeAt()

String이 담겨있는 변수에 charCodeAt(알고 싶은 index)를 이용해 사용해주면 된다.

Full Code

// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For Local Test
const input = 'A\n';
 
console.log(input.charCodeAt(0));
728x90

https://www.acmicpc.net/problem/1152

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/c81908a96f908c3376e82072963d96e52bcfd077

😢 문제를 보자마자 '이게 왜 정답 비율이 25%지?' 라고 생각하고 바로 풀었는데 틀렸다.
알아보니 ' '(space)만 들어오는 Test Case가 있어서 틀렸던 것이었다. 문제의 '예시 입력'에서 알려줬으면 더 좋았을 것 같다.

😊 if 조건문으로 '' 예외처리를 하였더니, 바로 정답. ' '(space)가 아니고 ''라는 것이 중요하다!
split(' ')을 사용하면, separator가 ' '(space)이기 때문에 입력값으로 ' '만 들어왔을 때 split된 array에는 [ '' ]만 들어가게 된다.
이 함정에 빠져서 다들 문제를 패스한 것 같다.

윗 줄을 Test 하기 위해 출력해보았다.


다른 풀이도 봤는데, 흠.. 조금 돌아가는 방법들이 많았다. length를 못 쓰는 경우가 없진 않을텐데..
웬만하면 다른 코드들도 참고해서 풀어보겠지만, 여기서는 개인적으로 필요성을 느끼지 못해 패스. 조금 더 생각해보자.

Full Code

// For submit
 
// const fs = require('fs');
// const input = fs
// .readFileSync('/dev/stdin')
// .toString()
// .trim()
// .split(' ');
 
// For Local Test
 
const example = 'The Curious Case of Benjamin Button\n';
// const example = ' ';
const input = example.trim().split(' ');
 
if (input[0] === '') {
console.log(0);
} else {
console.log(input.length);
}
728x90

https://www.acmicpc.net/problem/1065

Code

최종 제출 코드 https://github.com/DasolPark/Algorithm_JavaScript/blob/b9164f18301aec45680c44eeb204a6500f53bcdd/Baekjoon/1065.js
기존 제출 코드https://github.com/DasolPark/Algorithm_JavaScript/commit/95a24f7f1c0887af6d8a7e1a55e8533f0850150e

 

😢 '어떤 양의 정수 X의 자리수가 등차수열을 이룬다면'???? 지금 보면 별 것 아니지만, 처음 문제를 볼 때는 비슷한 문제를 풀어보지 못해서 그런지 이해하기 힘들었다. 문제 이해하는 것에 시간을 많이 보냈다.

😊 즉, 100미만의 수두 자릿수 또는 한 자릿수여서 등차수열을 확인할 수 없기 때문에 모두 '한수'가 된다.
그리고 세 자릿수부터 연속된 등차수열을 확인할 수 있다.
예를 들어, 우리에게 주어진 숫자 111을 백의 자리 1, 십의 자리1, 일의 자리1 하나씩 분리했다고 치자.
백의자리 1 - 십의자리 1 = 0 그리고 십의자리 1 - 일의자리 1 = 0 ( 1-1=0 === 1-1=0, true )
위처럼 연속된 두 개의 수 차이가 0으로 같다. 그렇다면 이건 한수이다.
그리고 1000은 '한수'가 아니다.

Solution 1) 기존 제출 코드
for loop안에서 100미만은 모두 한수로 count,
1000미만은 각 자릿수를 분리하여 Array에 넣고 각 자릿수 순서대로 빼주어 등차수열을 확인하였다.
만약 그 값이 한수라면 한수를 count해주었다. 그리고 1000은 한수가 아니기 때문에 else{ break; }으로 작성해주었다.

Solution 2) Other Solution
이 해결 방법은 다른 정답자의 답안을 참고하였다. 다른 방식으로 접근하였기 때문에 꼭 학습해두고 싶었다.
이 해결 방법에서는, classic for loop을 이용해서 function을 반복 호출하고 true값을 이용해 한수를 count해주었다.
특히, 세 자릿수가 들어오면 toString().split('').map을 이용해 Array로 만들어주고 값을 빼주어서 등차를 확인하였다.

Solution 3) 최종 제출 코드
Solution 2)의 개선 버전이다. for loop을 2번 사용하지 않고, function 안에서 한 번만 for loop을 사용했다.

자릿수를 다루는 문제와 직면할 때는, while을 이용하여 자릿수를 분리하거나
 문자열의 index를 이용하여 해결하곤 하는데, 항상 두 가지를 다 이용해보곤 한다.
프로그래밍은 한 가지 방법만 있지 않다는 게 가장 큰 매력인 것 같다.

Full Code

// Hansoo(category - function)
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const N = parseInt(fs.readFileSync('/dev/stdin').toString().trim());
 
function hansoo(N) {
const numArr = [];
let hansoo, digitCount;
let temp = 0;
 
for (let i = 1; i <= N; i++) {
if (i < 100) {
hansoo = i;
} else if (i < 1000) {
digitCount = 0;
temp = i;
while (temp > 0) {
numArr[digitCount] = temp % 10;
temp = parseInt(temp / 10);
digitCount++;
}
if (numArr[0] - numArr[1] === numArr[1] - numArr[2]) {
hansoo++;
}
} else {
break;
}
}
 
return hansoo;
}
 
// For Test
console.log(hansoo(110));
console.log(hansoo(1));
console.log(hansoo(210));
console.log(hansoo(1000));
 
// For submit
// console.log(hansoo(N));
 
// Other Solution(Solution 2)
 
// For submit
// const fs = require('fs');
// const N = parseInt(fs.readFileSync('/dev/stdin').toString().trim());
 
// For Test
// const N = 110;
 
// function findHansoo(N) {
// if (N < 100) {
// return true;
// } else {
// const numArr = N.toString()
// .split('')
// .map(num => {
// return parseInt(num);
// });
// if (numArr[0] - numArr[1] === numArr[1] - numArr[2]) {
// return true;
// }
// }
 
// return false;
// }
 
// let hansoo = 0;
// for (let i = 1; i <= N; i++) {
// if (findHansoo(i)) {
// hansoo++;
// }
// }
 
// console.log(hansoo);
 
// 2nd Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '1000';
 
// function hanCheck(num) {
// num = parseInt(num);
// let counter = 0;
// for (let i = 1; i <= num; i++) {
// if (i < 100) {
// counter++;
// } else if (i < 1000) {
// let temp = i;
// let numArr = [];
// let index = 0;
// while (temp > 0) {
// numArr[index] = temp % 10;
// temp = parseInt(temp / 10);
// index++;
// }
// if (numArr[0] - numArr[1] === numArr[1] - numArr[2]) {
// counter++;
// }
// }
// }
// console.log(counter);
// }
 
// hanCheck(input);
 
// 3rd Solution(최종 제출 코드)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '110';
// const N = parseInt(input);
 
// function hanCheck(N) {
// let hansoo = 0;
// for (let i = 1; i <= N; i++) {
// if (i < 100) {
// hansoo++;
// } else {
// const numArr = i
// .toString()
// .split('')
// .map(num => parseInt(num));
// if (numArr[0] - numArr[1] === numArr[1] - numArr[2]) {
// hansoo++;
// }
// }
// }
// console.log(hansoo);
// }
 
// hanCheck(N);
728x90

Q. 주어진 n만큼 1개씩 #(또는 *)을 계단모양으로 증가시켜라.
(n은 양수이며, 나머지 오른쪽 공백은 space로 입력)

--- Examples
steps(2)
'# '
'##'
steps(3)
'#  '
'## '
'###'
steps(4)
'#   '
'##  '
'### '
'####'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/2d0c64627731b45be6d9e0dbc2492c894d2a5846/exercises/steps/index.js

😢 도형은 신기하다. 쉬워보이는데, 해보면 생각보다 쉽지는 않다. 특히, 재귀사용을 위해서는 재귀에 대한 높은 이해가 필요하다.

😊 Solution 1)
중첩 for loop을 이용해서 간단하게 해결이 가능하다.
직사각형 형태이기 때문에, 외부 for loop과 내부 for loop 모두 0부터 그리고 n보다 작을 때까지 index를 증가시키면 된다.
그리고 내부 for loop에서 column(열)이 row(행)보다 작거나 같으면 '#'을, 크다면 ' '을 대입해주면 된다.

Solution 2)
재귀적 용법으로 문제를 해결했다.

먼저 row=0, stair=''로 default를 선언해준다.
그리고 만약 n이 row(행)와 같다면 함수를 return;해준다.(n만큼 행을 출력했으니까 더 이상 출력할 필요 없음)
그리고 만약 값을 저장하는 stair의 길이가 n과 같으면 row(행)+1함수를 실행시켜준다.
(여기서 return을 필수적으로 해줘야한다. 해주지 않으면 밑으로 내려가 불필요한 재귀를 다시 실행해주기 때문이다)
그 밑으로는 Solution 1)과 마찬가지로 stair.length가 row보다 작거나 같으면 '#', 아니라면 ' '를 대입해준다.
(stair.length는 Solution 1)의 column을 대체한다) 그리고 steps(n, row, stair+add)를 재귀적으로 실행하면 된다.

Full Code

function steps(n, row = 0, stair = '') {
if (n === row) {
return;
}
 
if (n === stair.length) {
console.log(stair);
return steps(n, row + 1);
}
 
const add = stair.length <= row ? '#' : ' ';
steps(n, row, stair + add);
}
 
// function steps(n) {
// for (let row = 0; row < n; row++) {
// let stair = '';
 
// for (let column = 0; column < n; column++) {
// if (column <= row) {
// stair += '#';
// } else {
// stair += ' ';
// }
// }
 
// console.log(stair);
// }
// }
728x90

Q. 주어진 String(문장)에서 각 단어의 첫 알파벳을 대문자로 바꿔라.

--- Examples
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/08ffc38c2f7b32b8baa35a6ecfc6c1d367559b1c/exercises/capitalize/index.js

😢 배열(Array)의 index을 이용해서 원초적 해결하려 했더니 조금 힘들었다.

😊 Solution 1)
입력받은 str을 split(' ')을 이용해 각 단어별로 나눠진 Array를 만들어주고,
for ... of loop 안에서 각 단어를 하나씩 가져와, 첫 번째 알파벳은 대문자로, 나머지 값은 slice(1)로 붙여주었다.
그리고 join(' ')을 이용해 다시 String(문장)으로 만들어 반환해주었다.

Solution 2)
classic for loop을 이용해 각 index의 앞(i-1)이 ' '(space)라면 해당 index(i)를 대문자로 변환하여 저장한다.
그게 아니라면, 해당 index(i)를 단순 저장해준다.

✔ toUpperCase()

소문자를 대문자로 변환해준다.

✔ split(' ')

String을 ' '(space)기준으로 나눠서 array에 저장해준다

✔ slice(1)

index 1부터 끝까지 모두 slice해준다

✔ for ... of

Array의 안에 있는 값을 index 순서대로 하나씩 가져온다

✔ join(' ')

' '(space)기준으로 Array를 String(문장)으로 합쳐준다

Full Code

function capitalize(str) {
let result = str[0].toUpperCase();
 
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === ' ') {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
 
return result;
}
 
// function capitalize(str) {
// const words = [];
 
// for (let word of str.split(' ')) {
// words.push(word[0].toUpperCase() + word.slice(1));
// }
 
// return words.join(' ');
// }
728x90

✨ Array의 모든 index에 값을 한 번에 채워주거나, 원하는 구간만큼 값을 채워줄 수 있는 helper method

(e.g., arr.fill(false) or arr.fill(0, 2, 4)) 왼쪽처럼 Array의 모든 값을 false로 채우거나, index 2부터 3까지 0을 채워줄 수 있다.
(Array.prototype.slice()와 마찬가지로 구간을 지정할 때, end-1까지 진행된다는 점을 명심하자)

💻Example Code

const arr = [ 1, 2, 3, 4, 5, 6 ];

console.log( arr.fill(0, 1, 3) );

실행 결과(index 1부터 3까지 지정했지만, 2까지 변한 것을 볼 수 있다)

😋 매우 큰 Array의 값을 한 번에 초기화 해줄 때, 또는 원하는 index 구간만큼 값을 바꿔줄 때 매우 유용하다.
백준 4673번 셀프 넘버(Self Number)문제를 풀 때 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

 

Array.prototype.fill()

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
728x90

Code

최종 제출 코드
기존 제출 코드

😢 무언가 원초적인 방법으로 풀었던 문제, 어떻게 풀어 나갈지에 대한 고민을 조금 했다.

😊 기존 제출 Solution) array를 선언하고, 모든 index 값을 0으로 초기화해준 후 Self Number가 아니라면 해당 index에 1을 넣어주었다.
그리고 마지막에 for loop의 i를 이용해 array[i]의 값이 1이 아니라면(=Self Number라면) Self Number인 i를 출력하도록 했다.

[추가] 최종 제출 Solution)
while loop 안에서 각 자릿수 나눠주기 + 나눠준 값 더하기를 진행하여 코드의 복잡도를 줄여줬다. 또한 시간도 더 빨라졌다.
그리고  배열 10000개 만큼 false로 채워주고, 셀프 넘버가 아니라면 true로 변경시켜주었다. 따라서 false로 남아있다면 그건 셀프 넘버다.


각 자릿수를 구하는 것은 매우 원초적인 방법으로 진행했다.
54321인 다섯 자리를 기준으로 설명하자면,
parseInt( 54321/10000 )(=5.4321)은 5
parseInt( (54321%10000) / 1000 )(=4.321)은 4
parseInt( (54321%1000) / 100 )(=3.21)은 3
parseInt( (54321%100) / 10 )(=2.1)은 2
54321 % 10 은 1
아래 Full Code에는 위의 자릿수 나누는 방식을, 다른 방법으로 접근한 Code가 있다.

✔ while loop을 이용한 자릿수 나누고, 바로 더하기

let temp = 나눌값;
let sum = temp;

while( 0 > temp){
sum += temp%10;
temp = parseInt(temp/10); }

또한, 다른 사람들이 푼 풀이가 매우 흥미로워서 그 방법들도 함께 연습했다. 세상에는 대단한 사람들이 참 많다.

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// Self Number
 
// 4th Solution
 
const n = 10000;
const isSelfNum = new Array(n + 1);
isSelfNum.fill(true);
 
function d(n) {
const N = n.toString().split('');
 
return n + N.reduce((acc, num) => (acc += +num), 0);
}
 
for (let i = 1; i <= n; i++) {
isSelfNum[d(i)] = false;
}
 
for (let i = 1; i <= n; i++) {
if (isSelfNum[i]) {
console.log(i);
}
}
 
// 3rd Solution
 
// function d(n) {
// let temp = n;
// let sum = temp;
 
// while (temp > 0) {
// sum += temp % 10;
// temp = parseInt(temp / 10);
// }
 
// return sum;
// }
 
// const N = 10000;
// const selfNumCheckArr = new Array(N);
// selfNumCheckArr.fill(false);
 
// for (let i = 1; i <= N; i++) {
// selfNumCheckArr[d(i)] = true;
// if (!selfNumCheckArr[i]) {
// console.log(i);
// }
// }
 
// 1st solution
 
// const N = 10000;
// let arr = [];
 
// for (let i = 0; i <= N; i++) {
// d(i);
// }
 
// function d(n) {
// if (n < 10) {
// arr[n + n] = 1;
// } else if (n < 100) {
// arr[n + parseInt(n / 10) + (n % 10)] = 1;
// } else if (n < 1000) {
// arr[n + parseInt(n / 100) + parseInt((n % 100) / 10) + (n % 10)] = 1;
// } else if (n < 10000) {
// arr[
// n +
// parseInt(n / 1000) +
// parseInt((n % 1000) / 100) +
// parseInt((n % 100) / 10) +
// (n % 10)
// ] = 1;
// } else {
// arr[
// n +
// parseInt(n / 10000) +
// parseInt((n % 10000) / 1000) +
// parseInt((n % 1000) / 100) +
// parseInt((n % 100) / 10) +
// (n % 10)
// ] = 1;
// }
// }
 
// for (let i = 1; i <= N; i++) {
// if (!(arr[i] === 1)) {
// console.log(i);
// }
// }
 
// 2nd solution(string - array[index])
 
// const N = 10000;
// const arr = [];
 
// for (let i = 0; i <= N; i++) {
// arr[i] = 0;
// }
 
// for (let i = 1; i <= N; i++) {
// d(i);
// }
 
// function d(n) {
// const str = n.toString();
 
// if (n < 10) {
// arr[n + n] = 1;
// } else if (n < 100) {
// arr[n + parseInt(str[0]) + parseInt(str[1])] = 1;
// } else if (n < 1000) {
// arr[n + parseInt(str[0]) + parseInt(str[1]) + parseInt(str[2])] = 1;
// } else if (n < 10000) {
// arr[
// n +
// parseInt(str[0]) +
// parseInt(str[1]) +
// parseInt(str[2]) +
// parseInt(str[3])
// ] = 1;
// } else {
// arr[
// n +
// parseInt(str[0]) +
// parseInt(str[1]) +
// parseInt(str[2]) +
// parseInt(str[3]) +
// parseInt(str[4])
// ];
// }
// }
 
// for (let i = 1; i <= N; i++) {
// if (arr[i] === 0) {
// console.log(i);
// }
// }
728x90

✨ pattern과 맞는 String을 교체해주는 helper method

(e.g., str.replace('dog', 'cat')) 왼쪽처럼 dog을 cat으로 교체하는 것이 가능하다.
간단하게 설명하자면,
첫 번째 parameter에는 RegExp(Regular Expressions) 또는 String을 넣을 수 있고(즉, 찾을 pattern)
두 번째 parameter에는 새로 넣을 new string을 넣을 수 있다(즉, 새로 넣을 replacement)

💻Example Code

1) 간단한 단어 교체

const str = 'Hi there!';
const afterReplace = str.replace('Hi', 'Hello');

console.log(afterReplace);

실행 결과(Hi가 Hello로 교체된 것을 볼 수 있다)

2) RegExp를 이용한 교체(alphabet만 남기기)

const strTwo = 'Hi! there~@!';
const afterReplaceTwo = strTwo.replace(/[^\w]/g, '');

console.log(afterReplaceTwo);

실행 결과(특수문자, 공백이 제거된 것을 볼 수 있다)

📌replace(/[^\w]/g, '')를 자세히 살펴보겠다.
1. RegExp의 시작과 끝은 /(slash)
2. []는 []안에 어느 것이라도 매치된다면 이라는 뜻이다. (다시 알아볼 필요가 있음)
3. ^ 는 무효화 시킨다는 뜻이다(반전이라고 생각하면 될듯하다)
4. \w은 글자와 숫자(alphanumeric)를 뜻한다.
5. g는 global이라는 뜻. 한 번 매치되어도 끝까지 매치되는 것을 찾게 한다.

즉, [^\w]을 이용해 글자와 숫자 이외의 모든 문자는 제거한다. 라고 보면 편하다.

😋 Anagrams(철자를 바꾼 말) Algorithm에서 공백, 구두점 그리고 특수문자를 제거하기 위해 사용하였다.
Regular Expressions은 문자열을 다루기에 매우 유용하다. 어렵기 때문에 하나씩 차근차근 쌓아가는 것이 필요하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

 

String.prototype.replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

 

RegExp

The RegExp constructor creates a regular expression object for matching text with a pattern.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

 

Regular expressions

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), search

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
728x90

✨ object의 keys 또는 values를 array로 반환하는 helper method

💻Example Code

const obj = { a: 'something', b: 2, c: 3 };

console.log( Object.keys(obj) );
console.log( Object.values(obj) );

실행 결과(keys와 values가 array로 반환되는 것을 볼 수 있다)

😋 Anagrams(철자를 바꾼 말) Algorithm 에서 같은 종류의 철자가 사용되었는지 확인할 때 유용하게 사용하였다.
(Algorithm 카테고리의 Anagrams Algorithm 문제에서 확인 가능하다)
이 외에도 다양한 곳에서 사용 가능하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

 

Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

 

Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26

+ Recent posts