Home > Article > Web Front-end > [Leetcode] Is Object Empty
Question Link: https://leetcode.com/problems/is-object-empty/description/
Given an object or an array, return if it is empty.
You may assume the object or array is the output of JSON.parse.
Sooo... we’re getting either an Array or an Object as the parameter to this function called obj. (Yeah, I know, super creative name, but it'll make sense later!)
Our task? Perform some magic coding tricks to first figure out if this obj is an array or an object. Then, based on that knowledge, we’ll decide what to do next.
Finally, we need to check if this object/array is empty or not. Simple, right? (Or is it...)
First things first: "An array is technically an object in JavaScript." Yep! That’s right—arrays are a special type of object in JS. So, don't get confused!
Object Detection 101: We can check if the parameter is actually an object (or array) by using typeof obj === 'object' && obj !== null. Why the !== null part? Well, because null is a special case in JS. Even though it's technically of type object, it's like the empty void of nothingness. So, we exclude that, just in case (even though the problem didn’t explicitly mention it, it’s a good habit).
Undefined and null Elements: Both objects and arrays can have properties/elements that are undefined or null. But no worries—they'll still count when we check the length. They don’t get a free pass from our validation!
Is it an Array?: We can check if the parameter is an array using Array.isArray(obj). No need to check again if it’s an object, though—we already did that earlier.
var isEmpty = function (obj) { if (typeof obj === "object" && obj !== null) { // Check if it's an object and not null if (Array.isArray(obj)) { // If it's an array return obj.length === 0; // Return true if it's empty } else { // If it's an object return Object.keys(obj).length === 0; // Return true if there are no keys } } return false; // If it's neither an object nor an array, return false };
Step 1: Check if it’s an object
First, we use typeof obj === 'object' && obj !== null to ensure the input is an object and not null. (Because we all know that typeof null === 'object is one of JavaScript’s weird quirks. Thanks, JavaScript!)
Step 2: Is it an array?
We use Array.isArray(obj) to distinguish between arrays and regular objects. Arrays have a length property, so we can directly check if obj.length === 0.
Step 3: Is it an object?
If it’s not an array, we check if it's an object using Object.keys(obj).length === 0. This method returns the number of keys in the object. No keys? It's empty!
Step 4: Default case
If the input isn’t an object (or it’s null), we return false because the question specifies we're working with either objects or arrays only.
The above is the detailed content of [Leetcode] Is Object Empty. For more information, please follow other related articles on the PHP Chinese website!