
- /**
- * 判断是否数组,例如[]
- * @author Rudon
- */
- function is_array (val) {
- // ES5方法
- return Array.isArray(val)? true: false;
- }
-
- /**
- * 判断是否对象,不包括数组,例如{}
- * @author Rudon
- */
- function is_object (val) {
- // ES5方法
- return (val instanceof Object && !Array.isArray(val))? true: false;
- }
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>JS判断是否数组、对象title>
- head>
- <body>
-
- <script>
-
-
- /**
- * 判断是否数组,例如[]
- * @author Rudon
- */
- function is_array (val) {
- // ES5方法
- return Array.isArray(val)? true: false;
- }
-
- /**
- * 判断是否对象,不包括数组,例如{}
- * @author Rudon
- */
- function is_object (val) {
- // ES5方法
- return (val instanceof Object && !Array.isArray(val))? true: false;
- }
-
-
-
- let a = [1,2,3]
- let b = {"name": "Kim", "age": 18}
- let c = null
- let d = 100
- let e = 'string'
-
- console.log('------------')
- console.log('是否数组', a,' >> ', is_array(a))
- console.log('是否数组', b,' >> ', is_array(b))
- console.log('是否数组', c,' >> ', is_array(c))
- console.log('是否数组', d,' >> ', is_array(d))
- console.log('是否数组', e,' >> ', is_array(e))
- console.log('------------')
- console.log('是否对象', a,' >> ', is_object(a))
- console.log('是否对象', b,' >> ', is_object(b))
- console.log('是否对象', c,' >> ', is_object(c))
- console.log('是否对象', d,' >> ', is_object(d))
- console.log('是否对象', e,' >> ', is_object(e))
-
-
- script>
-
- body>
- html>
分析三种判断数组的方法
http://t.zoukankan.com/ningyn0712-p-11827198.html
我们都知道instanceof是用来判断对象的类型的,并且所有的对象 instanceof Object结果都是true
内部机制是通过判断对象的原型链中是否能找到同类型的prototype
其原理是一层一层查找__proto__,如果和constructor.prototype的值相等则返回true,否则返回false
根据这一点可得,如果想判断一个对象是否是数组,需要判断这个对象的原型链上是否存在Array的原型:
console.log([] instanceof Array) // true
console.log([] instanceof Object) // true
很容易可以发现这个方法有个问题是无法判断对象是属于Object还是Array。
2. Array.isArray( obj )
obj是待检测的对象,如果结果返回Array则整体返回true,否则该表达式返回false。
ES5新增的方法
Array.isArray()优于instanceof的地方在于:Array.isArray()可以检测iframes