Jump to content
Sign in to follow this  
Pravin Kumar Raja

Checking for an Array

Recommended Posts

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?

Share this post


Link to post
Share on other sites

getElementsByTagName does not return an array, that's actually an HTMLCollection object.

Share this post


Link to post
Share on other sites

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>
	

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...