Illie
JS. 배열 객체 응용하기 본문
개요
지금까지 배운 배열 객체로 원하는 값을 출력하는 숙제이다
값을 출력할 때에는 다양한 방법을 사용해도 되지만, 유도하는 방법이 2가지 이상이어야 한다.
숙제는 총 6가지이며, 성공한 것과 실패한 것을 구별하겠다
숙제 1
주어진 배열 : arrBox = [100, 200, 300, 400, 500, 600, 700];
출력 : 300, 400
방법 1 splice()
arrBox11 = [100, 200, 300, 400, 500, 600, 700];
hw1_1 = arrBox11.splice(2, 2);
console.log(hw1_1)
위치 2에서부터 2가지 출력하기!
방법 2 slice()
arrBox13 = [100, 200, 300, 400, 500, 600, 700];
hw1_3 = arrBox13.slice(2, 4);
console.log(hw1_3);
위치 2에서 위치 4까지 출력하기!
실패 pop(_) 숫자넣기
arrBox12 = [100, 200, 300, 400, 500, 600, 700];
hw1_2 = arrBox12.pop();
console.log(hw1_2)
pop에 숫자넣어서 마지막 요소 3개 날리고 shift로 처음 요소 2개 날리려니 잘 안됐다!
숙제 2
주어진 배열 : arrBox = [100, 200, 300, 400, 500, 600, 700];
출력 : 100, 300, 500, 700
방법 1 : for 문
arrBox22 = [100, 200, 300, 400, 500, 600, 700];
for(i = 2; i < 7; i+=2){
console.log(arrBox22[i]);
}
i을 2씩 늘려하는 방법이 있다
방법 2 : filter()
arrBox23 = [100, 200, 300, 400, 500, 600, 700];
hw2_3 = arrBox23.filter(el => el %200 != 0);
console.log(hw2_3);
filter을 사용해서 200으로 나눠지지 않는 것들을 출력하면 된다
실패 사례
arrBox21 = [100, 200, 300, 400, 500, 600, 700];
if(arrBox21[i] % 200 !== 0){
console.log(i);
}
if문을 사용하고 싶었으나 어떻게 해야할지 모르겠다
if문이 직관적인거 같으면서도 내 마음대로 잘 안된다
숙제 3
주어진 배열 : arrBox = [100, 200, 300, 400, 500, 600, 700];
출력 : 700
방법 1 : pop()
arrBox31 = [100, 200, 300, 400, 500, 600, 700];
hw3_1 = arrBox31.pop();
console.log(hw3_1);
pop으로 마지막 요소를 잘랐다(?)
방법 2 : slice()
arrBox32 = [100, 200, 300, 400, 500, 600, 700];
hw3_2 = arrBox32.slice(6);
console.log(hw3_2);
slice로 간단하게 잘랐다
숙제 4
주어진 배열 : arrBox4 = ["j", "b", "c", "d", "e"];
출력 : "j"
방법 1 :shift()
arrBox41 = ["j", "b", "c", "d", "e"];
hw4_1 = arrBox41.shift();
console.log(hw4_1);
방법 2 : reduce()
arrBox42 = ["j", "b", "c", "d", "e"];
hw4_2 = arrBox42.reduce(el => el);
console.log(hw4_2);
뭔가 reduce를 악용한 기분이 든다
숙제 5
주어진 배열 : arrBox4 = ["j", "b", "c", "d", "e"];
출력 : "j", "c"
방법 1 : find() + concat()
arrBox51 = ["j", "b", "c", "d", "e"];
hw5_1 = arrBox51.find(el => el == "j");
hw5_2 = arrBox51.find(el => el == "c");
hw5_3 = hw5_1.concat(hw5_2);
console.log(hw5_3);
이건 순서대로 나열된게 아니라서 그런지 어렵네
방법 2 : for()
arrBox55 = ["j", "b", "c", "d", "e"];
for(i = 0; i < 3; i+=2){
console.log(arrBox55[i]);
}
더하기로 해버리기~~
실패 사례
arrBox55 = ["j", "b", "c", "d", "e"];
hw5_4 = arrBox55.filter(el => el == "j" && "c");
console.log(hw5_4);
arrBox54 = ["j", "b", "c", "d", "e"];
if(arrBox54 = "j" || "c"){
console.log(arrBox54);
}
왜... 아무것도... 되지... 않는가...
숙제 6
주어진 배열 : arrBox4 = ["j", "b", "c", "d", "e"];
출력 : "j" "b" "c" "d"
방법 1 : pop ()
arrBox61 = ["j", "b", "c", "d", "e"];
hw6_1 = arrBox61.pop();
console.log(arrBox61);
방법 2 : for ()
arrBox62 = ["j", "b", "c", "d", "e"];
for(i = 0; i<4; i++){
console.log(arrBox62[i]);
}
지금 생각해보니 filter도 가능할 것 같다
'JAVASCRIPT > 자바스크립트' 카테고리의 다른 글
searchEffect03 - charAt() (0) | 2022.02.08 |
---|---|
searchEffect02 - includes (11) | 2022.02.07 |
searchEffect01 - indexOf() (11) | 2022.02.07 |
JS. 오늘의 공부 정리 (0) | 2022.02.04 |
JS. for문으로 1부터 100까지 합 구하기 (0) | 2022.02.03 |
Comments