JS-undefined/null

川长思鸟来 2023-10-18 16:29 147阅读 0赞

JS-undefined/null

    • 转换成数字的时候
    • 意义不同
      • null表示该对象不存在
      • undefined表示该变量已经定义但是没有值
    • 例子

if 判断语句中,两者都会被转换为false

转换成数字的时候

  1. null是一个表示无的对象,转换为数值为0
  2. undefined表示一个无的原始值,转化为数值为NAN(与任何数字相加也为NAN
  3. Number(null)输出为0, Number(undefined)输出为NaN

意义不同

null表示该对象不存在

  1. 1.作为函数的参数,表示该函数的参数不是对象
  2. 2.作为对象原型链的终点

undefined表示该变量已经定义但是没有值

情形如下

  1. 1.变量被声明了但是没赋值时
  2. 2.调用函数时,应该提供的参数没提供,则该参数为undefined
  3. 3.函数没有返回值时,默认返回undefined
  4. 4.对象没有赋值的属性

例子

  1. /*以下例子均是在谷歌浏览器中的控制台中输出 第一行为待验证代码 第二行为结果*/
  2. null
  3. null
  4. var hong;
  5. undefined
  6. //定义一个函数 可以通过shift + enter 不执行回车
  7. function test(a) {
  8. console.log(a);
  9. }
  10. undefined
  11. //调用函数
  12. test();
  13. //输出没有定义
  14. VM205:2 undefined
  15. //返回没有定义
  16. undefined
  17. //调用没有定义的对象
  18. var obj = {
  19. };
  20. undefined
  21. obj.h;
  22. undefined
  23. //null的类型是对象
  24. typeof null
  25. "object"
  26. //null和undefined是相等,毕竟undefined是从null派生出来的,所以把它们定义为相等的
  27. null == undefined
  28. true
  29. //在一些情况下,我们一定要区分这两个值,那应该使用===不转换类型直接进行比较 或者使用typeof null == typeof undefined
  30. null === undefined
  31. false
  32. //即使强制复制为null仍然会输出undefined
  33. var n = null
  34. undefined
  35. //字符串与没有定义的直接相连会直接报错
  36. 'test'+abc
  37. VM2380:1 Uncaught ReferenceError: abc is not defined
  38. at <anonymous>:1:8
  39. (anonymous) @ VM2380:1
  40. //而如果跟未赋值的变量会出现直接加上undefined
  41. 'test'+undefined
  42. "testundefined"

发表评论

表情:
评论列表 (有 0 条评论,147人围观)

还没有评论,来说两句吧...

相关阅读