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


    效果图

    方法

    1. /**
    2. * 判断是否数组,例如[]
    3. * @author Rudon
    4. */
    5. function is_array (val) {
    6. // ES5方法
    7. return Array.isArray(val)? true: false;
    8. }
    9. /**
    10. * 判断是否对象,不包括数组,例如{}
    11. * @author Rudon
    12. */
    13. function is_object (val) {
    14. // ES5方法
    15. return (val instanceof Object && !Array.isArray(val))? true: false;
    16. }

    完整例子

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>JS判断是否数组、对象title>
    8. head>
    9. <body>
    10. <script>
    11. /**
    12. * 判断是否数组,例如[]
    13. * @author Rudon
    14. */
    15. function is_array (val) {
    16. // ES5方法
    17. return Array.isArray(val)? true: false;
    18. }
    19. /**
    20. * 判断是否对象,不包括数组,例如{}
    21. * @author Rudon
    22. */
    23. function is_object (val) {
    24. // ES5方法
    25. return (val instanceof Object && !Array.isArray(val))? true: false;
    26. }
    27. let a = [1,2,3]
    28. let b = {"name": "Kim", "age": 18}
    29. let c = null
    30. let d = 100
    31. let e = 'string'
    32. console.log('------------')
    33. console.log('是否数组', a,' >> ', is_array(a))
    34. console.log('是否数组', b,' >> ', is_array(b))
    35. console.log('是否数组', c,' >> ', is_array(c))
    36. console.log('是否数组', d,' >> ', is_array(d))
    37. console.log('是否数组', e,' >> ', is_array(e))
    38. console.log('------------')
    39. console.log('是否对象', a,' >> ', is_object(a))
    40. console.log('是否对象', b,' >> ', is_object(b))
    41. console.log('是否对象', c,' >> ', is_object(c))
    42. console.log('是否对象', d,' >> ', is_object(d))
    43. console.log('是否对象', e,' >> ', is_object(e))
    44. script>
    45. body>
    46. 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

  • 相关阅读:
    130道基础OJ编程题之: 29 ~ 38 道
    【C++】类和对象——拷贝构造函数
    浅谈 Hive 数据倾斜原因及解决方案
    抖音小程序开发教学系列(3)- 抖音小程序页面开发
    总结一下 vue2 组件之间的通信
    是什么让 NFT 项目成为“蓝筹”?
    C#:模式匹配与模式
    LQ0112 立方和【进制】
    找出一段英文文本中出现次数最多的10个单词
    node 第十二天 npm补充 详解package-lock.json在团队协作中的作用
  • 原文地址:https://blog.csdn.net/qq285744011/article/details/126723777