How to check if an object is an array or not? Provide some code
How to check if an object is an array or not? Provide some code
To check if an object is an array in JavaScript, you can use the Array.isArray()
method. This method is the most reliable and straightforward way to determine if a given value is an array. It returns true
if the value is an array; otherwise, it returns false
.
Here is an example of how to use Array.isArray()
:
// Example variables
var myArray = [1, 2, 3];
var notArray = {name: "John", age: 30};
// Check if the variables are arrays
console.log(Array.isArray(myArray)); // Output: true
console.log(Array.isArray(notArray)); // Output: false
Array.isArray(myArray)
checks if myArray
is an array. Since myArray
is indeed an array, it returns true
.Array.isArray(notArray)
checks if notArray
is an array. Since notArray
is an object and not an array, it returns false
.Array.isArray()
is part of ECMAScript 5 (ES5) and is fully supported in all modern browsers, including Chrome, Firefox, IE (from version 9 onwards), and others[1][2][3][7]. This method does not check the prototype chain of the value, making it a reliable option for type-checking arrays even when dealing with different execution contexts, such as iframes or other global contexts[7].
While Array.isArray()
is the recommended approach, there are other methods that were historically used before Array.isArray()
became standard:
instanceof
:
console.log(myArray instanceof Array); // Output: true
console.log(notArray instanceof Array); // Output: false
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào