Problem
Description
Given an object or an array, return if it is empty.
- An empty object contains no key-value pairs.
- An empty array contains no elements.
You may assume the object or array is the output of JSON.parse.
Example 1:
Input: obj = {"x": 5, "y": 42}
Output: false
Explanation: The object has 2 key-value pairs so it is not empty.
Example 2:
Input: obj = {}
Output: true
Explanation: The object doesn't have any key-value pairs so it is empty.
Example 3:
Input: obj = [null, false, 0]
Output: false
Explanation: The array has 3 elements so it is not empty.
Constraints:
objis a valid JSON object or array2 <= JSON.stringify(obj).length <= 105
Starter
/**
* @param {Object|Array} obj
* @return {boolean}
*/
var isEmpty = function(obj) {
};
Solution
1. 物件與陣列
在 JavaScript 中,所有基本型別 (Primitives) 以外的值都是物件[1]。
陣列為高階(high-level)、似列表(list-like)的物件[2]。
- 物件:一個物體,由鍵與值構成與描述[3]。
「屬性(Property)」是物件的組成單位,每個屬性都包含兩個部分:
1. 鍵(key):名稱,用來識別這個屬性。
2. 值(value):該屬性所儲存的資料。
- 陣列:一個清單,由元素和索引構成[3]。
陣列的內部結構
陣列實際上是這樣的物件結構:
const arr = ['A', 'B', 'C', 'D'];
// 陣列內部類似於:
// {
// '0': 'A',
// '1': 'B',
// '2': 'C',
// '3': 'D',
// length: 4
// }
// 陣列的索引 (0, 1, 2...) 實際上就是物件的屬性名稱
console.log(arr[0]); // 'A'
console.log(arr['0']); // 'A' (用字串索引也可以)
2. Object.keys()
語法
Object.keys(obj)
- 參數:
obj- 回傳其可列舉屬性的物件。 - 回傳值:回傳一個包含物件內所有可列舉屬性的字串陣列。
基本使用範例
用於物件:
Object.keys({}) // []
Object.keys({ a: 1, b: 2 }) // ["a", "b"]
用於陣列:
Object.keys([]) // []
Object.keys([1, 2, 3]) // ["0", "1", "2"] // 返回索引值(字串形式)
Object.keys(['a', , 'c']) // ["0", "2"] // 跳過空位
也就是說:
- 空物件
{}→Object.keys()的函式回傳值是空陣列[] - 空陣列
[]→Object.keys()的函式回傳值也是空陣列[]
3. .length
基本概念
陣列(Array)才有 .length 屬性,用於表示陣列的長度,其值為最大數字索引 + 1。
const arr = ['a', 'b', 'c'];
console.log(arr.length); // 3
Code
/**
* @param {Object|Array} obj
* @return {boolean}
*/
var isEmpty = function(obj) {
return Object.keys(obj).length === 0;
};
References
[1] 重新認識 JavaScript: Day 04 物件、陣列以及型別判斷
[3] 六角學院 - 物件與陣列設計
喜歡我的文章,拍五下~
![物件 from 六角學院 [3]](https://resize-image.vocus.cc/resize?norotation=true&quality=80&url=https%3A%2F%2Fimages.vocus.cc%2F267767cb-bb7a-410c-8529-d6360c5dd692.jpg&width=740&sign=ikn77a0hwUvEP0xk620_b--kgJcgmq9rQNSikPDnXvc)
![陣列 from 六角學院 [3]](https://resize-image.vocus.cc/resize?norotation=true&quality=80&url=https%3A%2F%2Fimages.vocus.cc%2F5660ab6a-dfd6-45a2-9b4c-3216f2c572c4.jpg&width=740&sign=swm68GN1evNTJg8jbshfvjREKb1p8e5x8XSF3fj7dIo)
















