본문 바로가기

언어/Javascript

(24)
[짧] apply에 관해.. 문제를 풀고 다른 사람이 작성한 답을 보다가 헷갈리는 부분이 있어 포스팅합니다. TIP ) [...Array(5).keys()]; // range(5) let tube1 = Array.apply(null, Array(t)); let tube2 = Array(t).fill(undefined); let tube3 = Array(t) console.log(tube1) // [undefined x t] console.log(tube3 // [undefined x t] console.log(tube3) // [empty x t] tube1과 tube2는 동일하게 undefined로 채워집니다. https://school.programmers.co.kr/learn/courses/30/lessons/17687 해당 ..
[클린코드 자바스크립트] 함수 함수 인자를 던져줄 때, 객체 구조분해로 넘길 수있다. 여기서 조금더 안전하게 쓰기 위해선 그 인자값이 비어있다면 throw를 던져주어도 좋다. 위 사진은 required 함수를 따로 선언하여 필수인 요소들을 기입하지 않는다면 throw 예외를 주는 코드이다. 기본값 사용하기 => || 또는 ?? 써도 좋다. (앞선 포스팅서 다룸) 또는 = 로 넣을 수도 있다. const func = function ( {name = "" , age = 0 , height = 0 } = {} ) { ...some logic } // 기본값이 각각 "", 0, 0 으로 기입. // 아예 아무것도 기입하지 않는다면 빈객체가 인자의 기본 값이 된다.0
async 콘솔에 찍어본 기록 그냥 소소한 정리이다. 눈으로 확인해본 기록. async function f() { console.log("async function f 시작"); let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("완료!"), 1000) }); let result = await promise; // 프라미스가 이행될 때까지 기다림 (*) console.log("await이후의 function f"); console.log(result); // "완료!" } async function a(){ console.log("async function a 시작"); } f(); a(); async함수 내의 await을 만나면 프라미스가 처리되길 기..
PS속 스프레드 문법과 Rest문법 분석 과정 function solution(land) { lengthFourArray = Array(4).fill(0).map((cur, idx) => cur + idx); lengthLandArray = Array(land.length).fill(0).map((cur,idx) => cur + idx); for (let land_height_idx of lengthLandArray){ if (land_height_idx === 0) continue; for (let land_weight_idx in lengthFourArray){ let maxValue = 0; for (let idx of lengthFourArray){ if (land_weight_idx != idx){ if (maxValue < land[lan..
집합의 교집합 차집합 대칭차집합 자바스크립트로 PS문제를 풀다가, 정리해보고자 한다. 아래는 두 집합에서 중복되는 요소의 개수에 따른 등 수를 메기는 로직이다. 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/77484?language=javascript function solution(lottos, win_nums) { const rank = [6,6,5,4,3,2,1] const countZero = lottos.filter((ele) => ele === 0).length; concideCase = lottos.filter((ele) => win_nums.includes(ele)).length; return [rank[concideCase + countZero], ra..
Array.prototype.join() Array.prototype.join() PS할 때 유용할 것 같아 적어둔다. 파이썬의 "".join()과 값을 출력할때 *arr와 같은효과를 낼 수 있다 const arr = [1,2,3,4,5]; arr.join(); // "1,2,3,4" arr.join("") // "1234" // python 처럼 요소 타입이 char가 아니어도 가능. // *arr하려면 arr.join(" ");
prototype.includes(), in 연산자, hasOwnProperty(), Array.prototype.some in 연산자는 객체에 사용하는 용도 이다. 즉 객체가 갖는 프로퍼티와 메소드 존재 여부를 검증해 true, false로 리턴한다. 이 때 주의할 점은 배열 사용시, 내용이 아닌 인덱스 값을 검증한다. var soccerplayer = new Array("nedved", "ronaldo", "ronaldinho", "henry", "jisungpark"); "henry" in soccerplayer // false length in socerplayer // true 즉 내용을 찾는 검증을 위해 쓰면 안되고, 프로퍼티가 있는지, 메소드가 존재하는지를 검증하기 위해 사용해야만 한다. 그렇다면 문자열이나 배열에서 값을 검증하고 싶을 때는 어떻게 하나ㅏ? 그럴 때, ES6에서 추가 된 메서드 includes()..
.sort() function solution(d, budget) { let count = 0; for (let value of d.sort()){ budget -= value if (budget >= 0){ count ++; continue } break } return count } 다음과 같이 제출을 했더니, 분명 파이썬 그대로 옮겨왔는데도 틀렸다. 의심가는 곳은 딱 한 곳 뿐이었다. 정렬 반환을 조금 다르게 하나? 찾아보았다. 자바스크립트의 sort함수는 기본적으로 배열을 문자열로 간주하고 정렬을 진행한다. 이는 파이썬 배열안에 문자열로 가득찬 것을 정렬할 때를 생각해보면 될 것이다. 이렇게 되면 문제가 [199999999, 9]를 sort하면(디폴트 값은 오름차순), [199999999, 9] 그대로 도출되는..