split(), map(), while(), Math.floor(), for문 변수 선언 위치

suyeon·2022년 1월 17일
0

1. split(), map()

input = [ '1 1', '2 3', '3 4', '9 8', '5 2' ]

input[cnt].split(" ")
// input= [ '1', '1' ] [ '2', '3' ] [ '3', '4' ] [ '9', '8' ] [ '5', '2' ]
input[cnt].split(" ").map(Number);
// [ 1, 1 ] [ 2, 3 ] [ 3, 4 ] [ 9, 8 ] [ 5, 2 ]

2. .map(Numbers)

const strNumArr = ["2", "4", "6", "8", "10"];
const numArr = strNumArr.map(Number);

console.log(numArr); //[2, 4, 6, 8, 10];

3. while()
배열에서 while문을 사용할때는 i++, length--를 해줘야 무한반복이 일어나지 않는다!

let length = input.length;
let i=0;

while (length>0) {
    let array=input[i].split(' ').map(Number)
    console.log(array[0] + array[1]);
    i ++;
    length --;
}

4. Math.floor()로 나눗셈 몫 구하기

console.log(Math.floor(5.95));
// expected output: 5

console.log(Math.floor(5.05));
// expected output: 5

console.log(Math.floor(5));
// expected output: 5

console.log(Math.floor(-5.05));
// expected output: -6

5. while문 break
while문을 빠져나갈때는 if() 조건문을 사용하여 break; 한다.

let origin = Number(input[0]);
let count = 0;

while(true) {
    let sum = Math.floor(input/10) + (input%10);
    input = (input%10)*10 + (sum%10);
    count++;
    if(origin === input) break;
}
console.log(count);

6. for문 변수 선언 위치

변수 값 초기화를 for문 밖에 해줘야한다!

let nums = input.map(Number);

ans = nums[0]; // 선언을 밖에 해줘야 했다.
let cnt = 0;

for (var i=1; i<9; i++) {
    // ans = nums[0]; WRONG!
    if (ans < nums[i]) {
        ans = nums[i];
        cnt = i;
    }
}

console.log(ans, cnt+1);

0개의 댓글