자바스크립트 기본 파일 입출력
전체 텍스트 읽어 온 다음 줄바꿈 기호를 기준으로 구분해서 리스트 변환
let fs = require('fs');
let input = fs.readFileSync('input.txt').toString().split('\n');
//let input = fs.readFileSync('/dev/stdin').toString().split('\n'); //백준용
console.log("input");
📃input.txt
123
456
789 999
🧾출력
['123', '456', '789 999']
예시
let fs = require('fs');
let input = fs.readFileSync('input.txt').toString().split('\n');
//let input = fs.readFileSync('/dev/stdin').toString().split('\n'); //백준용
let line = input[0].split(" ");
let a = parseInt(line[0]);
let b = parseInt(line[1]);
console.log(a + b)
📃input.txt
1 2
🧾출력
3
한 줄씩 입력을 받아서, 처리하여 정답을 출력할 때는 readline 모듈
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on('line', function(line) {
input.push(line);
}).on('close', function() {
console.log(input);
process.exit();
});
최대, 최소, 합
let data = [1, 2, 3, 4, 5];
//최소값 구하기
let minValue = data.reduce((a, b) => Math.min(a, b))
console.log(minValue);
//최대값 구하기
let maxValue = data.reduce((a, b) => Math.max(a, b))
console.log(maxValue);
//합구하기
let sumValue = data.reduce((a, b) => a + b, 0);
console.log(sumValue);
set
let mySet = new Set();
mySet.add(3);
mySet.add(4);
mySet.add(5);
mySet.add(1);
console.log(`원소의 개수 : ${mySet.size}`);
console.log(`원소 5 포함 여부 ${mySet.has(5)}`); //true / false 반환
mySet.delete(5);
for (let item of mySet) {
console.log(item);
}
소수점 출력 : Number.prototype.toFixed()
let a = 12345.6789;
console.log(a.toFixed(2));
//소수점 두번째짜리까지 출력
//12345.68
특정문자 반복하기 : String.prototype.repeat()
const data = "test".repeat(5);
console.log(data);
//출력 : testtesttesttesttest
양끝 공백 제거하기 : String.prototype.trim()
const data = " test ";
console.log(data);
console.log(data.trim());
//📃 출력
// test
//test
배열 초기화 : Array.prototype.fill()
//길이 10, 모든 뭔소의 값 0 초기화
let arr = new Array(10).fill(0);
console.log(arr);
배열 하나의 값으로 초기화 : Array.from()
let arr = Array.from({ length: 5 }, () => 7)
console.log(arr)
//출력
//[ 7, 7, 7, 7, 7 ]
이차원 배열 생성 및 초기화
let arr = Array.from(Array(4), () => new Array(5))
console.log(arr)
//출력
// [
// [ <5 empty items> ],
// [ <5 empty items> ],
// [ <5 empty items> ],
// [ <5 empty items> ]
// ]
let arr2 = Array.from(Array(4), () => Array.from({ length: 5 }, () => 7))
console.log(arr2)
//출력
// [
// [ 7, 7, 7, 7, 7 ],
// [ 7, 7, 7, 7, 7 ],
// [ 7, 7, 7, 7, 7 ],
// [ 7, 7, 7, 7, 7 ]
// ]
let arr3 = Array.from(Array(4), () => new Array(5).fill(0))
console.log(arr3)
//출력
// [
// [ 0, 0, 0, 0, 0 ],
// [ 0, 0, 0, 0, 0 ],
// [ 0, 0, 0, 0, 0 ],
// [ 0, 0, 0, 0, 0 ]
// ]
let arr4 = new Array(3);
for (let i = 0; i < arr4.length ; i++) {
arr4[i] = Array.from(
{length: 4},
(undefined, j) => i * 4 + j
);
}
console.log(arr4)
//출력
//[ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9, 10, 11 ] ]
배열 이어 붙이기 :Array.prototype.concat(), 전개연산자...
//concat
let arr1 = [1, 2, 3, 4, 5]
let arr2 = [6, 7, 8, 9, 10]
let conSum = arr1.concat(arr2, [22, 23], [33])
console.log(conSum)
//출력
//[
// 1, 2, 3, 4, 5, 6,
// 7, 8, 9, 10, 22, 23,
// 33
//]
전개연산자
let dotSum = [...arr1, ...arr2]
console.log(dotSum);
//출력
//[
// 1, 2, 3, 4, 5,
// 6, 7, 8, 9, 10
//]
배열 뒤에서 출력 : Array.prototype.at()
배열 길이로도 가져올 수 있지만, 파이썬 처럼 음수 값을 이용해서 뒤에서부터 가져올 수도 있다.
let array = [0, 1, 2, 3, 4];
console.log(array[array.length -1]); // 4
const array1 = [5, 12, 8, 130, 44];
let index = 2;
console.log(`${array1.at(-1)}`);
console.log(`${array1.at(-2)}`);
console.log(`${array1.at(-3)}`);
'코테풀이 > 자바스크립트 코테 전환' 카테고리의 다른 글
자바스크립트 큐 구현하기 (0) | 2023.04.27 |
---|---|
[자바스크립트 | 프로그래머스 1단계] 정수 내림차순으로 배치하기, 자연수 뒤집어 배열로 만들기 (0) | 2022.08.07 |
[자바스크립트 | 프로그래머스 1단계] 가장 작은수 제거하기 (0) | 2022.08.07 |
[자바스크립트 | 프로그래머스 1단계] 평균구하기 (0) | 2022.08.06 |
[자바스크립트 | 프로그래머스 1단계] 하샤드 수 (0) | 2022.08.06 |
자바스크립트 코딩테스트 정리