-2

Sometimes it is necessary to determine what type of data a variable contains, in this specific case we are talking about the Array type.

How can I end in the different scenarios if the variable is Array type? I'm talking about scenarios, I'm talking about jQuery, Angular, TypeScript, CoffeeScript, etc.

Thank you!

Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73

1 Answers1

-2

There are different forms depending on the library, framework or language to use.

Here it will compile a list of the different ways to verify if the variable is of type array.

jQuery (since v1.3)

var value = [];
if ($.isArray(value)) {
    console.log('this variable is a array');
}

Angular

$scope.value = [];
if (angular.isArray($scope.value)) {
    console.log('this variable is a array');
}

Angular2

value = [];
if (Array.isArray(value)) {
    console.log('this variable is a array');
}

ECMAScript 5, ECMAScript 6 and TypeScript

var value = [];
if (Array.isArray(value)) {
    console.log('this variable is a array');
}

CoffeeScript

value = []
if {}.toString.call(value) is '[object Array]'
    console.log 'this variable is a array'

CoffeeScript(as function)

Array.isArray || ( value ) -> return {}.toString.call(value) is '[object Array]'
value = []
if Array.isArray(value)
    console.log 'this variable is a array'

Object.prototype

var value = [];
if( Object.prototype.toString.call( value ) === '[object Array]' ) {
    alert( 'Array!' );
}

Pure javascript:

function isArray(value) {
    return !!value && Array == value.constructor;
}

var value = [];
if (isArray(value)) {
    console.log('this variable is a array');
}
Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73