Pravin Kumar Raja Posted November 5, 2019 Share Posted November 5, 2019 This is in connection with the web page https://www.w3schools.com/js/js_arrays.asp. Array.isArray function does not return correct true when its argument is an array of object. What can be the reason? Is it a bug? A method suggested by W3ishools to use a tailor-made function function isArray(x) { return x.constructor.toString().indexOf("Array") > -1; } which also does not work, as in the code given below: <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>This "home made" isArray() function returns true when used on an array:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = isArray(document.getElementsByTagName("p")); function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } </script> </body> </html> The function returns false. What is a foolproof method to check whether a variable is an array? Link to comment Share on other sites More sharing options...
Ingolme Posted November 5, 2019 Share Posted November 5, 2019 getElementsByTagName does not return an array, that's actually an HTMLCollection object. Link to comment Share on other sites More sharing options...
JMRKER Posted November 10, 2019 Share Posted November 10, 2019 If you really need an array, you can convert from a collection to an array with the ES6 spread function. <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>This "home made" isArray() function returns true when used on an array:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; // not used in this demonstration document.getElementById("demo").innerHTML = isArray(document.getElementsByTagName("p")); // false var parasCollection = document.getElementsByTagName('p'); // same as above document.getElementById("demo").innerHTML += '<br>' + isArray(parasCollection); // false var paraArray = [...parasCollection]; // convert collection to an array document.getElementById("demo").innerHTML += '<br>' + isArray(paraArray) + '<br>'; // true // shows tagName of collection array for (var i=0; i<paraArray.length; i++) { document.getElementById('demo').innerHTML += '<br>' + paraArray[i].tagName +' '; } function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } </script> </body> </html> Link to comment Share on other sites More sharing options...
Pravin Kumar Raja Posted April 1 Author Share Posted April 1 Thanks for the help. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now