zoukankan      html  css  js  c++  java
  • Null和undefined的区别?

    undefined的中场景

    1.变量被声明了,但没有赋值时,就等于undefined

    //打印a的时候,找到a了 但是找不到a的值,所以返回一个undefined
    var a;
    console.log(a);
    console.log(a+1);//undefined+1 计算不了

    //不声明b,直接使用b,js直接报错 ReferenceError: b is not defined
    //说明完全没有找到b这个变量 代码报错停止运行
    console.log(b)

    2.调用函数时,应该提供的参数没有提供,该参数等于undefined

    // 声明函数使用function关键字 函数没有调用是完全不执行的
    function add(a,b) {
    console.log(a)
    console.log(b)
    alert(a+b);
    }
    // 调用函数 函数名+() 传入参数
    add(1,2);

    //再次调用函数(没有给够参数)
    add(1);*/

    3.对象没有赋值的属性,该属性的值为undefined

    // 创建一个对象
    var yourGirlFriend={
    name:"lily",
    age:18,
    length:180
    }
    // console.log(yourGirlFriend.name);
    console.log(yourGirlFriend.color);*/

    4.函数没有返回值时,默认返回undefined

    function reduce(a,b) {
    // 函数只要不写return 就没有返回值
    alert(a-b);
    // return a-b;//返回a-b
    }
    // 调用函数
    var num1=reduce(4,2);
    console.log(num1)

    console.log(reduce(4,1));

    常见的 null 环境

    1.作为函数的参数,表示该函数的参数不是对象

    function fn(a,b) {
    alert(a+b);
    }
    // 需要传递参数,但是我们暂时不想传递,或者不需要传递,那么我们可以传一个空对象null
    fn(null,null)

    /*ajax有个方法send(),send方法参数是你要向服务器传递的值
    但是get方法是在地址栏拼接值,所以不需要send传递,所以我们在send中写一个参数null,告诉他我不想在这里传*/

    2.作为对象原型链的终点

    //比如:"123"--->String--->Object--->null

    3.如果定义的变量准备在将来用于保存对象,那么最好将该变量初始化为null而不是其他值

    var a = null;
    function fn1() {
    a=2;
    }
    fn1();
    console.log(a);

  • 相关阅读:
    ECharts之柱状图 饼状图 折线图
    Vue自定义指令(directive)
    HDU 1231 最大连续子序列
    POJ 2533 Longest Ordered Subsequence
    HDU 1163 Eddy's digital Roots
    HDU 2317 Nasty Hacks
    HDU 2571 命运
    HDU 4224 Enumeration?
    HDU 1257 最少拦截系统
    HDU 2740 Root of the Problem
  • 原文地址:https://www.cnblogs.com/fsg6/p/12988486.html
Copyright © 2011-2022 走看看