Câu hỏi phỏng vấn Javascript
Câu hỏi

How to check if an object is an array or not? Provide some code

Câu trả lời

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():

javascript Copy
// 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

Explanation

  • 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.

Additional Information

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].

Alternative Methods

While Array.isArray() is the recommended approach, there are other methods that were historically used before Array.isArray() became standard:

  1. Using instanceof:
    javascript Copy
    console.log(myArray instanceof Array); // Output: true
    console.log(notArray instanceof Array); // Output: false
    However, `...
junior

junior

Gợi ý câu hỏi phỏng vấn

junior

Is there anyway to force using strict mode in Node.js?

middle

Explain the differences on the usage of foo between function foo() {} and var
foo = function() {}

expert

Does JavaScript pass by references or pass by values?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào