Jump to content

Checking for an Array


Pravin Kumar Raja

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?

Link to comment
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>
	

 

Link to comment
Share on other sites

  • 4 years later...

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...