JavaScript/Null

来自康健生活
Kangkk​(留言 | 贡献)2020年6月2日 (二) 11:46的版本 (→前言)

前言

在计算机科学中,null函数(或null运算符)是使程序状态保持不变的子例程。当它是处理器指令集的一部分时,称为NOP或NOOP(无操作)。

Mathematically, a (computer) function f is null if and only if its execution leaves the program state s unchanged. That is, a null function is an identity function whose domain and codomain are both the state space S of the program, and for which:

f(s)=s for all elements s∈S.

零字节(0x00)

char A[8] = ""; unsigned short B = 1979; Initially, A contains nothing but zero bytes, and B contains the number 1979.

variable name A
value [null string]
hex value 00 00 00 00 00 00 00 00

Null 表示“一个空对象指针”、“没有对象”、“空值”等概念,是一种特殊的对象值。

NULL是个没有值的值( NULL is a value that is not a value. )。

NULL 在其他语言中的变体,包括但不限于:NULL, nil, None, Nothing, Nil, nullptr等(C/C++:NULL, Lua: nil, python:None, VB:Nothing, ObjectC:Nil, C++11: nullptr)。

Null 使用 typeof 判断时结果是 object,因为 Null 被转换为机器语言时是很多个 0,而只要前三个为零的话,就会被机器语言判断为 object ?(未确定) 。

在 JavaScript 设计之初,使用的是 32 位操作系统,为了性能考虑使用低位存储?(未确定) 变量的类型信息,其中 000 开头代表对象,恰好 Null 转换成机器语言时是很多

ISO / IEC 9899第7.17条第3款: NULL ...扩展为实现定义的空指针常量

强制类型转换

原始类型被强制转换成 Number 类型:

模板:Leftrightflex

缺点

  • 破坏类型(subverts types)
    跳过了类型检测,直到程序运行抛出 NULL 引用错误。
  • 草率的(is sloppy)
    只要语言允许任意对象可以是 NULL。NULL 与空字符容易混为一谈。
    if(str==null || str.equals("")){}
    
    if(string.IsNullOrEmpty(str)){}
    
  • 特例(is a special case)
    NULL 是一个没有值的值,在许多情况下 NULL 变成了一个需要特别处理的地方。
    char c = 'A';
    char *myChar = &c;
    std::cout<<*myChar<<std::endl;
    char *myChar = 123;
    std::cout<<*myChar<<std::endl; // ==> 编译错误
    char *myChar = 0;
    std::cout << *myChar << std::endl;  // ==> 运行错误
    
  • 使API捉襟见肘(makes poor APIs)
  • 加剧了不好的编程策略(exacerbates poor language decisions)
  • 难以调试(is difficult to debug)
  • 不可组合的(is non-composable)