배열기초 /타입 1 , 배열기초 1-3
2020. 7. 4. 13:27ㆍRetrospection/Sprint
배열기초 / 타입
1.
주어진 파라미터의 타입을 리턴하는 함수를 작성하시오.
파라미터가 array 일 경우 array 를 리턴해야함
function getType(anything) {
if (Array.isArray(anything)) {
return 'array';
}else {
return typeof anything;
}
}
Array.isArray - 배열과 객체를 구분하기 위하여 사용.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
Array.isArray()
Array.isArray() 메서드는 인자가 Array인지 판별합니다.
developer.mozilla.org
배열기초
1.
Write a function called "getLastElement
Given an array, "getLastElement" returns the last element of the given array
Notes:
- If the given array has a length of 0, it should return 'undefined'.
-1-
function getFirstElement(array) {
return array[0]
}
내가 짠 코드는 1번 인데 여기는 array 의 길이가 0일 경우가 없다.
밑에가 array 길이가 0일경우를 조건문으로 넣어준 코드이다 .
-2-
function getFirstElement(array) {
if(array.length === 0){
return undefined;
}else{
return array[0]
}
}
2.
Write a function called "getLastElement".
Given an array, "getLastElement" returns the last element of the given array.
Notes:
- If the given array has a length of 0, it should return 'undefined'.
function getLastElement(array) {
if (array.length === 0){
return undefined;
}else {
return array[array.length - 1];
}
}
문제를 너무 복잡하게 생각하고 검색을 하다가 여러가지 복잡해보이는 코드를 봤는데
그냥 array.length 라고 써서 하면 되는거였다.
시도하기전에 미리 안될거라고 생각하지말고
생각대로 해보고 일단 안되면 다른방법을 찾아보자
3.
Write a function called "getNthElement".
Given an array and an integer, "getNthElement" returns the element at the given integer, within the given array.
Notes:
- If the array has a length of 0, it should return 'undefined'.
function getNthElement(array, n) {
if(array.length === 0){
return undefined;
}else {
return array[n];
}
}
문제가 쉬워서 특별히 코멘트 할 것이 없음.
'Retrospection > Sprint' 카테고리의 다른 글
3. 배열의 반복 1 , 2 (0) | 2020.07.04 |
---|---|
3. 반복문 1~3 (0) | 2020.07.04 |
2. 타입 1 ~3 (0) | 2020.07.02 |
2. 수학 - 1~3. (0) | 2020.07.02 |
1. 문자열 7 , 8 (0) | 2020.06.28 |