var num1 = Math.abs(-1); //음수
var num2 = Math.abs('-1'); //문자형 숫자
var num3 = Math.abs('ABC'); //문자
var num4 = Math.abs(null); //null
console.log(num1, num2, num3, num4) // 1 1 NaN 0
function solution(array, n) {
return array.reduce((a,c)=> Math.abs(a-n) < Math.abs(c-n) ? a : Math.abs(a-n) === Math.abs(c-n) ? Math.min(a, c) : c);
}
나는 10줄이 넘어가는데 이렇게 풀수있다니...
reduce 메서드의 파라미터에 초기값을 작성하지 않으면 c는 첫번째값부터 시작한다. 따라서 0부터 시작해서 a의 값을 변경하는 것이다.
삼항연산자를 사용해서 a와 c에서 각각 n을 뺀값의 절대값을 비교하고 c의 경우가 더 크다면 이전에 구한 두가지의 값이 같은지 확인(절댓값이 같은 수가 있는지를 확인하는 작업)하고 있다면 그 둘중에 작슨수를 리턴하고, 아니라면 a값을 c로 변경한다.
이렇게 반복을 거치면 최종적으로 c를 리턴하게 되는 것이다.
function solution(array, n) {
const absList = array.map(data => Math.abs(data)-n)
// 항목을 절댓값으로 변경하고 n만큼 뺀값으로 교체한 배열
const dabList = absList.map(data => Math.abs(data))
// 정확한 비교를 위해서 한번더 모든 항목을 절댓값을 교체한 배열
//// 절댓값이 같은 항목이 있는지 체크하는 과정
const minIndex = dabList.indexOf((Math.min.apply(null,dabList)))
// n과 가장 가까운 조건을 만족하는 숫자가 위치한 첫번째 인덱스
const maxIndex = dabList.lastIndexOf((Math.min.apply(null,dabList)))
// n과 가장 가까운 조건을 만족하는 숫자가 위치한 마지막 인덱스
// 만약 그 둘이 다르다면 값이 2개가 존재한다는 뜻
if (minIndex !== maxIndex){
// 그 둘을 비교해서 작은 것을 리턴
return Math.min(array[minIndex],array[maxIndex])
}
else{
// 두개의 값이 같다면 그냥 minIndex에 위치한 배열의 값을 리턴한다.
return array[minIndex]
}
}
indexOf()
와 lastIndexOf()
를 활용해서 절댓값이 같은 숫자가 존재하는지 여부를 파악하고 그에따라 리턴값을 다르게 설정하는 방식으로 풀었다.
이 긴 코드가 한문장으로도 같은 기능을 수행한다는 사실을 알게되면 허탈함이 배가된다.
주어진 함수의 테스트를 통과하는 요소만 모아서 새로운 배열로 반환하는 메서드.
원하지 않는 값을 조건을 통해 제거할수 있다.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toUpperCase());
// expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
let str = 'HELLO WORLD'
console.log(str.toLowerCase())
// hello world
input을 입력하는 부분의 길이가 끝까지 늘어나지 않는 현상이 생겼고 width를 100%로 늘려도 변동하지 않음
전체의 display가 flex
였기 때문에 flex-grow
의 값을 1로 해줘서 최대로 늘리는것까지는 좋았지만,
이렇게 placeholder
가 가운데오 와버렸다. 내가 원하는 것은 왼쪽으로 치우쳐져 있는 것인데, 하고 다시 살펴보다가 input의 길이 자체를 100%로 늘려서 구현에 성공했음.
내용을 둘러싸는 껍데기를 100%로 했으니 내용물이 늘어나지 않았던 것이다.
const data = {
string: '123',
number: 123,
boolean: true,
null: null,
undefined: undefined,
symbol: Symbol('Hello'),
bigint: 123n,
array: [],
object: {},
function: function () {}
}
function checkType(d) {
return Object.prototype.toString.call(d).slice(8, -1)
}
console.log(checkType(data.string) === 'String')
console.log(checkType(data.string)) // 'String'
console.log(checkType(data.number)) // 'Number'
console.log(checkType(data.boolean)) // 'Boolean'
console.log(checkType(data.null)) // 'Null'
console.log(checkType(data.undefined)) // 'Undefined'
console.log(checkType(data.symbol)) // 'Symbol'
console.log(checkType(data.bigint)) // 'BigInt'
console.log(checkType(data.array)) // 'Array'
console.log(checkType(data.object)) // 'Object'
console.log(checkType(data.function)) // 'Function'
const 변수
let 변수
if
, else
키워드를 사용해서 구문을 작성한다.
if(option){
//option의 값이 참이면 실행되는 내용
}
if(option){
// option의 값이 참이면 실행되는 내용
} else{
// option의 값이 거짓일때 실행될 코드
}
if(option){
// option의 값이 참이면 실행되는 내용
} else if(option 2){
// option 2 의 값이 참 일때 실행될 코드
} else if(option 3){
// option 3 의 값이 참 일때 실행될 코드
}
switch
,case
,break
,default
키워드를 써서 구문을 작성한다. switch(option){
case 값1:
// option의 값이 '값1'이면 실행되는 구문
break // 동작했다면 여기서 종료!
case 값2:
// option의 값이 '값2'이면 실행되는 구문
break
case 값3:
// option의 값이 '값3'이면 실행되는 구문
break
default:
// option의 값이 세가지 모두 해당되지 않으면 실행되는 구문
for(시작 조건; 종료 조건; 증감){
// code
}
for( let i = 0; i < 10; i += 1) {
console.log(i)
}
// 0 1 2 .... 9
전체 반복을 종료함
for (let i = 0; i < 10; i += 1) {
if (i > 5) {
break
}
console.log(i)
}
// 0
// 1
// 2
// 3
// 4
// 5
for (let i = 0; i < 10; i += 1) {
if (i % 2 === 0) {
continue
}
console.log(i)
}
// 1
// 3
// 5
// 7
// 9
현재 반복을 종료하고 다음 반복으로 넘어감
for (v of strlist){
answer.push(v.length)
}
const user = {
name: 'jyc',
age: 28,
isValid: true,
email: 'jyc4648@gmail.com'
}
for (const key in user) {
console.log(key, user[key])
}
// name jyc
// age 28
// isValid true
// email jyc4648@gmail.com
주의 - 잘못 사용하면 무한 루프에 빠져서 컴퓨터 크래쉬 될수 있음
while(option){
//
}
기호 | 뜻 |
---|---|
+ | 더하기 |
- | 빼기 |
* | 곱하기 |
/ | 몫 |
% | 나머지 |
const a = 2
: 'const 형태로 선언한 a라는 변수에 2라는 값을 할당
하거라'
=
let hamburger = 3
console.log(hamburger++) // 3?? 먼저 값출력하고 난 다음에 더해
console.log(hamburger) // 4
console.log(++hamburger) // 4?? 먼저 더한다음에 출력해
console.log(hamburger) // 4
hamburger++
과 ++hamburger
는 달라요