判断是数组还是对象的方法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43572937/article/details/102682436
  1. instanceof操作符
function arrORobj (n) {
	return	n instanceof Array === true ? '数组' : '对象';
}
  1. 使用constructor属性
function arrORobj (n) {
	if(n.constructor === Array) {
		return '数组';
	} else if(n.constructor === Object)) {
		return '对象';
	}
	return '既不是数组也不是对象';
}
  1. 调用Object.prototype.toString()的方法
function arrORobj (n) {
	if(Object.prototype.toString.call(n) === '[object Array]') {    //注意: 前一个object首字母是小写
		return '数组';
	} else if(Object.prototype.toString.call(n) === '[object Object]') {
		return '对象';
	}
	return '既不是数组也不是对象';
}
  1. ES6提供的Array.isArray()方法
function arrORobj (n) {
	return Array.isArray(n) ? '数组' : '对象';
}

猜你喜欢

转载自blog.csdn.net/weixin_43572937/article/details/102682436