I am trying to create a function which console.log object or an array type
function whichDataStructure (ITEM){
if (typeof ITEM ==='object'){
console.log ('I am object');
} if (typeof ITEM === 'array') {
console.log ('i am array');
} else {
console.log(' neither');
}
};
In Javascript Arrays are actually a kind of Object.
You have to use the Array.isArray()
function to find out if a value is an Array:
function whichDataStructure(item) {
if (Array.isArray(item)) {
console.log('I am an Array');
} else if (typeof item === 'object'){
console.log('I am an Object');
} else {
console.log('I am of type: ' + typeof item);
}
};
It is important that you test if the value is an Array before testing if it is an Object. Otherwise it will always be seen as an Object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.