상세 컨텐츠

본문 제목

[자바스크립트] 문제들

카테고리 없음

by esoesmio 2023. 5. 2. 16:39

본문

x는 0부터시작 y는 10부터시작

5,5에서 멈추도록

 




for (let x = 0, y = 10; x <= y; x++, y--) {
console.log(x, y);
}

 

 



const number1 배열은 1,2,3,4,5,6

복사해서 3,4,5,6,7,8 인 배열을 만들어라
 
 
 



const numbers1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const numbers2 = [];

for (let num of numbers1) {
num++; // ⚠️ 복사된 값. let 사용 주목
numbers2.push(num + 1);
}
console.log(numbers1, numbers2);


 

 

 

 

1부터 10중에 3의배수만 빼고 출력해라

 

for (let i = 1; i <= 10; i++) {
if (i % 3 === 0) continue;
console.log(i);
}

console.log('for 루프 종료');
 
 

 

1부터 10까지수를 출력하는데 5에서 끝나게 만들어라

for (let i = 1; i <= 10; i++) {
if (i === 5) break;
console.log(i);
}

 

14 이하의 수에서 홀수만 출력

 

// 짧게 짠 수정 코드
let x = 0;
while (x < 14) {
if (++x % 2 === 0) continue;
if (x > 8) break;
console.log(x);
}

 

 

함수로 인자를 넣었을때 홀인지 짝인지

 

function isOdd (x) {
return !!(x % 2);
}

let num = 12;

console.log(
`${num}()${
isOdd(num) ? '' : ''
}수입니다.`
);

 

 

 

할당함수로 인자로 받는 수가 홀수인지 짝수인지, 2로 나눈 나머지로 조사해 트루인지 폴스인지 리턴

 

function isOddNum (number) {
console.log(
(number % 2 ? '' : '')
+ '수입니다.'
);
return number % 2 ? true : false;
};

const checkIfOdd = isOddNum; // 뒤에 괄호 없음 유의


console.log(checkIfOdd(10));
 
객체의 요소값으로 함수가 나오는 예를 만들어라
 

let person = {
name: '홍길동',
age: 30,
married: true,
introduce: function (formal) {
return formal
? '안녕하십니까. 홍길동 대리라고 합니다.'
: '안녕하세요, 홍길동이라고 해요.';
}
};

console.log(person.introduce(true));
console.log(person.introduce(false));

 

 

 

 

더하기 빼기 나누기 곱하기 함수를 가진 배열을 만들고 for문으로 5,3넣은것을 출력

 

let arithmetics = [
(a, b) => a + b,
(a, b) => a - b,
(a, b) => a * b,
(a, b) => a / b
];

for (arm of arithmetics) {
console.log( arm(5, 3));
}

 

 

객체의 프로퍼티에 접근하는법

저는 몇살이고 기혼입니다. 를 써봐라

name: '홍길동',
age: 30,
married: true,

 

 

let person = {
name: '홍길동',
age: 30,
married: true,
introduce: function () {
return `저는 ${this.name}, ${this.age}살이고 `
+ `${this.married ? '기혼' : '미혼'}입니다.`;
}
}

console.log(person.introduce());

 

고차함수, 콜백함수를 이용해서 [1,2,3,4,5] 에 있는것들이 출력되는걸 해라

 

let list = [1, 2, 3, 4, 5];

function doInArray (array, func) {
for (item of array) {
func(item);
}
}

// console.log - console이란 객체에서 log란 키에 할당된 함수
doInArray(list, console.log);

 

 

 

익명함수로 3 , 5, 3 로

곱하기 나누기로 해서

함수의 결과값을 받는걸 다시 for안의 함수로 넣어서

40 0.625

값이 나오도록 해라

 

 

 

더하기 빼기 곱하기 함수들을 인자, 홀수인지 양수인지 판단하는 함수를 인자, 로 넣어서 5,7로 만들어봐라

 

 

// calculate
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;

// evaluate
const isOdd = (number) => !!(number % 2);
const isPositive = (number) => number > 0;

function calcAndEval (calc, eval, x, y) {
return eval(calc(x, y));
}

console.log(
calcAndEval(add, isOdd, 5, 7),
calcAndEval(subtract, isPositive, 5, 7),
calcAndEval(multiply, isOdd, 5, 7)
);

 

 

function을 결과값으로 반환할 수 있는 함수를 만들어라. boolean을 인자값으로 받고 그거에 따라 삼항 연산자로 펑션 둘중 하나 고르는거

이걸로 함수 안에 리턴값이 함수이면 어떻게 호출하는지도 보여줘라

 

 

function getIntroFunc (name, formal) {
return formal
? function () {
console.log(`안녕하십니까, ${name}입니다.`);
} : function () {
console.log(`안녕하세요~ ${name}이라고 해요.`);
}
}

// const hongIntro = getIntroFunc('홍길동', true);
// const jeonIntro = getIntroFunc('전우치', false);

const hongIntro = getIntroFunc('홍길동', true);
const jeonIntro = getIntroFunc('전우치', false);

hongIntro();
jeonIntro();

 

플로스 마이너스 곱하기 나누기를

한 함수 안에서 리턴값으로 두 인자를 받아서 나오게 만들어라

 

const add = (a, b) => a + b;
const sub = (a, b) => a - b;
const mul = (a, b) => a * b;
const div = (a, b) => a / b;

function comb3ArmFuncs(armFunc1, armFunc2, armFunc3) {
return (x, y) => armFunc3(armFunc2(armFunc1(x, y), y), y);
}

const add_mul_sub = comb3ArmFuncs(add, mul, sub);
const mul_add_div = comb3ArmFuncs(mul, add, div);
const div_add_mul = comb3ArmFuncs(div, add, mul);

console.log(
add_mul_sub(10, 4),
mul_add_div(10, 4),
div_add_mul(10, 4)
);

 

(a+b)*c-d를 커링함수로 작성

 

 

 

// 기존의 코드
function addMultSubt (a, b, c, d) {
    return (a + b) * c - d;
}

const addMultSubt2 = (a, b, c, d) => (a + b) * c - d;

console.log(
    addMultSubt(2, 3, 4, 5),
    addMultSubt2(2, 3, 4, 5),
);

// ⭐ 커링으로 작성된 함수
function curryAddMultSubt (a) {
    return function (b) {
        return function (c) {
            return function (d) {
                return (a + b) * c - d;
            }
        }
    }
}

const curryAddMultSubt2 = a => b => c => d => (a + b) * c - d;

console.log(
    curryAddMultSubt(2)(3)(4)(5),
    curryAddMultSubt2(2)(3)(4)(5)
);

const curryAddMultSubtFrom2 = curryAddMultSubt(2);
const curryMultSubtFrom5 = curryAddMultSubt(2)(3);
const currySubtFrom20 = curryAddMultSubt(2)(3)(4);

console.log(curryAddMultSubtFrom2);
console.log(curryMultSubtFrom5);
console.log(currySubtFrom20);
// 화살표 함수로 바꾸어 다시 실행해 볼 것

console.log(
    curryAddMultSubtFrom2(3)(4)(5),
    curryMultSubtFrom5(4)(5),
    currySubtFrom20(5)
);

 

기본값이 있는 add에 매개변수 없음, 1,  1,3 이 있게 해서

 

function add(a = 2, b = 4) {
    console.log(`${a} + ${b}`);
    return a + b;
}

console.log(
    add(),
    add(1),
    add(1, 3)
);

 

 

여기에 들어있는

console.log(
'4.', add(1, 3, 5, 7)
);

 

1357 을 arguments로 하나하나 나오게 하고

그 [0]을 나오게하고 arguments의 type를 알아내라.

 

 

function add(a, b) {
console.log('1.', arguments);
console.log('2.', arguments[0]);
console.log('3.', typeof arguments);
return a + b;
}

console.log(
'4.', add(1, 3, 5, 7)
);

 

 

 

add()가 인자를 두개만 받는데  인자를 4개를 넣어버림. 그러면 그안에 있는거 다출력하고 a+b 리턴하는걸 만들어라

 

 

function add(a, b) {
for (const arg of arguments) {
console.log(arg);
}
return a + b;
}

console.log(
add(1, 3, 5, 7)
);

 

 

 

arguments.length를 이용해서 

 

1,4,7의 평균

24,31,52,80 dml vudrbs

 

 

 

function getAverage() {
let result = 0;
for (const num of arguments) {
result += num;
}
return result / arguments.length;
}

console.log(
getAverage(1, 4, 7),
getAverage(24, 31, 52, 80)
);

 

그것을 또 타입에 안전하게 한 버전

 

 

 

// 💡 타입에 안전한 버전
function getAverage() {
let result = 0, count = 0;
for (const num of arguments) {
if (typeof num !== 'number') continue;
result += num;
count++;
}
return result / count;
}

console.log(
getAverage(2, '', 8, true, 5)
);

 

주함수는 인자가 없는데  함수만 잇도록 걸래나고 첫번재 인자와 두번째 인자를 함수,  // 그 다음꺼를 또함수// 그 다음꺼롤 또함수

const add_mul = combineArms(add, mul, 1, true);
const add_mul_sub = combineArms(add, mul, sub);
const add_mul_sub_div = combineArms(add, mul, sub, div);

이런식으로 만들어라

 

 

 

 

const add = (a, b) => a + b;
const sub = (a, b) => a - b;
const mul = (a, b) => a * b;
const div = (a, b) => a / b;
function combineArms () {
    return (x, y) => {
        let result = x;
        for (const arm of arguments) {
            if (typeof arm !== 'function') continue;
            result = arm(result, y);
        }
        return result;
    }
}
const add_mul = combineArms(add, mul, 1, true);
const add_mul_sub = combineArms(add, mul, sub);
const add_mul_sub_div = combineArms(add, mul, sub, div);

// 💡 익명 함수 사용됨
const add_mul_sub_div_pow
    = combineArms(add, mul, sub, div, (x, y) => x ** y);
console.log(
    add_mul(8, 3),
    add_mul_sub(8, 3),
    add_mul_sub_div(8, 3),
    add_mul_sub_div_pow(8, 3)
);

 

 

 

classIntro(3, '김민지', '영희', '철수', '보라')
이거를 넣으면
1. [ '영희', '철수', '보라' ]
2. [Arguments] { '0': 3, '1': '김민지', '2': '영희', '3': '철수', '4': '보라' }
3. 3반의 선생님은 김민지, 학생들은 영희, 철수, 보라입니다.

이렇게 출력되게 해봐라

 

 

 

 

console.log(
    '3.',
    classIntro(3, '김민지', '영희', '철수', '보라')
); // 호이스팅

function classIntro (classNo, teacher, ...children) {
    console.log('1.', children);
    console.log('2.', arguments);

    let childrenStr = '';
    for (const child of children) {
        if (childrenStr) childrenStr += ', ';
        childrenStr += child;
    }
    return `${classNo}반의 선생님은 ${teacher}, `
        + `학생들은 ${childrenStr}입니다.`
}

 

 

 

주함수는 인자가 없는데  함수만 잇도록 걸래나고 첫번재 인자와 두번째 인자를 함수,  // 그 다음꺼를 또함수// 그 다음꺼롤 또함수

 

이런식으로 만들어라

 

위위문제와 똑같은건데

const add_mul = combineArms(add, mul, 1, true);
const add_mul_sub = combineArms(add, mul, sub);
const add_mul_sub_div = combineArms(add, mul, sub, div);

이거 안해도 되고

console.log(
doMultiArms(8, 3, add, mul, 1, true),
doMultiArms(8, 3, add, mul, sub),
doMultiArms(8, 3, add, mul, sub, div),
doMultiArms(8, 3, add, mul, sub, div, (x, y) => x ** y)
);

이것만 해도 될수있게..

... 넣어서 할 수 있게 해라

 

 

 

 

 

 

 

const add = (a, b) => a + b;
const sub = (a, b) => a - b;
const mul = (a, b) => a * b;
const div = (a, b) => a / b;

function doMultiArms (x, y, ...arms) {
  let result = x;
  for (const arm of arms) {
    if (typeof arm !== 'function') continue;
    result = arm(result, y);
  }
  return result;
}

console.log(
  doMultiArms(8, 3, add, mul, 1, true),
  doMultiArms(8, 3, add, mul, sub),
  doMultiArms(8, 3, add, mul, sub, div),
  doMultiArms(8, 3, add, mul, sub, div, (x, y) => x ** y)
);

 

 

 

 

 

 

 

중첩함수를 한번 만들어보아라 cl 

 

이렇게나오게

 

function outer () {
const name = '바깥쪽'
console.log(name, '함수');

function inner () {
const name = '안쪽'
console.log(name, '함수');
}
inner();
}

outer();

 

 

 

 

 

재귀함수를 한번 만들어봐라

 

function upto5 (x) {
console.log(x);
if (x < 5) {
upto5(x + 1);
} else {
console.log('- - -');
};
}

upto5(1);
upto5(3);
upto5(7);

 

재귀함수로 팩토리얼 한번 만들어봐라

 

 

function fact(x){

return x===0?1:x*fact(x-1)


}

console.log(fact(4));
 
 

 

 

즉시실행함수 써서

8월 1일의 평균기온은 XX도입니다 이거 출력하게 해라

 

let initialMessage;

{
const month = 8;
const day = 15;
const temps = [28, 27, 27, 30, 32, 32, 30, 28];
let avgTemp = 0;
for (const temp of temps) {
avgTemp += temp
}
avgTemp /= temps.length;

initialMessage = `${month}${day}일 평균기온은 섭씨 ${avgTemp}도입니다.`;
};

console.log(initialMessage);
console.log(month); // 새로고침 후 const var로 바꾸고 실행해볼 것

 

 

 

 

{}에서 키값을 객체 또는 배열로 해서

프로퍼티리를 꺼내는걸 한번 해봐라

 

const objKey = { x: 1, y: 2 };
const arrKey = [1, 2, 3];

const obj = {
[objKey]: '객체를 키값으로',
[arrKey]: '배열을 키값으로'
}

console.log(
obj[objKey],
obj[arrKey]
);

// ⚠️ ???????
console.log(
obj[{ }], // 내용이 다른 객체
obj['1,2,3'] // 문자열
);

// 로그를 펼쳐 키값을 볼 것 - 💡 문자열임
// 객체와 배열이 그 자체가 아니라 문자열로 치환되어 키가 되는 것
console.log(obj);
console.log(
obj['[object Object]']
);

 

 

객체 선언시 프로퍼티 키와 대입할 상수 변수 명이 동일할때

 

 

 

const x = 1, y = 2;

const obj1 = {
x: x,
y: y
}

console.log(obj1);

const obj2 = { x, y }

console.log(obj2);

 

 

function createProduct (name, price, quantity) {
return { name, price, quantity };
}

const product1 = createProduct('선풍기', 50000, 50);
const product2 = createProduct('청소기', 125000, 32);

console.log(product1, product2);

 

 

객체 안에 메서드를 불러오는거

 

// 일반 함수 프로퍼티 정의
const person = {
name: '홍길동',

salutate: function (formal) {
return formal
? `안녕하십니까, ${this.name}입니다.`
: `안녕하세요, ${this.name}이에요.`;
}
}
console.log(person.salutate(true));

 

 

 

// ⭐️ 메서드 정의
const person = {
name: '홍길동',

salutate (formal) {
return formal
? `안녕하십니까, ${this.name}입니다.`
: `안녕하세요, ${this.name}이에요.`;
}
}
console.log(person.salutate(true));

 

 

 

 

 

댓글 영역