본문 바로가기

Programing/JavaScript

[JavaScript] 빈 배열인지 확인하는 법

Array.isArray(arr) && arr.length === 0   으로 조건을 엮으면 됩니다. 

arr가 배열이라면 arr.length === 0로 넘어가서 조건을 확인한다. 배열일 경우 length가 0인지 확인한다.

Javascript는 && 문 왼쪽에 있는 조건을 먼저 검사하고 true 일때만 다음 조건을 검사하기 때문입니다. 

배열이 Array일 경우에만, length 프로퍼티가 있는지 확인하기에 에러가 나지 않습니다.


arr.length로 하면 변수 arr가 배열값이 아닌경우 오류를 발생하기 때문에 위의 식대로 써줘야한다.




* 관련 문제  (Pre Course JavaScript Basic / 069_getAllButLastElementOfProperty)


Write a function called "getAllButLastElementOfProperty".


Given an object and a key, "getAllButLastElementOfProperty" returns an array containing all but the last element of the array located at the given key.


Notes:

* If the array is empty, it should return an empty array.

* If the property at the given key is not an array, it return an empty array.

* If there is no property at the key, it should return an empty array. 



답 :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function getAllButLastElementOfProperty(obj, key) {
  
  if(Array.isArray(obj[key]) === false ||   // 만약 obj[key]값이 배열이 아니거나
  Array.isArray(obj[key]) && obj[key].length === 0 ||   // obj[key]값이 배열인데 obj[key].length 배열길이가 0 이거나 (빈값이라면)
  obj[key] === null) {   // obj[key] 값이 존재하지 않다면
    
    return [];   // 빈 배열을 반환한다.
  }
  
  obj[key].pop();
  return obj[key];
 
}
 
 
var obj = {
  key: []
};
var output = getAllButLastElementOfProperty(obj, 'key');
console.log(output); // --> [1,2]
 
cs