Home  >  Article  >  Web Front-end  >  A deeper understanding of primitive types in JS

A deeper understanding of primitive types in JS

青灯夜游
青灯夜游forward
2021-02-02 18:01:442947browse

A deeper understanding of primitive types in JS

The primitive types in JavaScript include Undefined, Null, Number, Boolean and String. Other variables are reference types, that is, Object Type. Primitive types are saved in "stack memory", while reference types are saved in "heap memory", but usually when using variables in JavaScript, the location of the variable in memory is not very concerned.

The "typeof" operator is used to obtain the data type of the variable's value. typeof can accept variable names or literal values ​​as operands and return a string describing the variable type information. It should be noted that the return value of typeof does not correspond to the type in JavaScript:

  • "undefined" - the variable value is undefined

  • "number" ——The variable value is a numerical value

  • "boolean" ——The variable value is a Boolean value

  • "string" ——The variable value is a string

  • "object" ——The variable value is an object or null

  • "function" ——The variable value is Function

In addition, typeof is an operator like (,-), not a function. Although the usage of "typeof(12)" will not cause an error, it is Operator "typeof 12" is the appropriate way to use it.

1, undefined and null

The definition of Undefined Type in the ECMA-262 document is:

The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined. . For variables that have not been declared using var, using it will generate an error, but using the typeof operator will return "undefined":

var foo;
alert(foo);        // undefined
alert(bar);        // 错误
alert(typeof foo); // undefined
alert(typeof bar); // undefined
undefined is implemented as a global variable (rather than a literal value like null), Its value is "undefined". In ECMAScript 3, undefined can be assigned other values, and has been corrected to be read-only in ECMAScript 5.

Null Type also has only one value, null, which is used to represent "null value". Most programming languages ​​have literals like null, nil, etc. used to represent empty values. But unlike other programming languages, JavaScript does not use null to represent the value of an uninitialized variable (represented by undefined).

The logical meaning of null is to represent a null object pointer. The usual objects in JavaScript do not include simple data types, so logically null means that the variable points to an Object type with a null value (not a literal "{}").

For this reason, you can understand why using the typeof operator to obtain the type of a null value will result in "object". The meaning of null value in JavaScript for Object type is similar to 0 for Number type and "" for String type.

Both undefined and null are used to describe "null value", but in a logical sense, undefined is more "low-level" than null. Under normal circumstances, there is no need to explicitly specify the variable value as undefined.

For a variable that is intended to save an Object but does not actually point to an object, the variable value should be set to null to reflect the role of null as a null object pointer and to distinguish it from undefined.

2. Numerical value

ECMAScript uses a simplified numerical model. It has only one numeric type, Number, without separating out a separate integer type. In terms of implementation, the Number type adopts the 64-bit double-precision floating point format defined by the IEEE 754 standard.

In the 64-bit floating point format, 52 bits are used to represent the mantissa, 11 bits represent the exponent, and 1 bit is the sign. Therefore, when representing integers, the range of integers that JavaScript can represent is between -Math.pow(2,53) and Math.pow(2,53). Beyond this range, the accuracy of low-digit numbers cannot be guaranteed.

var n = Math.pow(2,53); // 9007199254740992
alert(n === n + 1);     // true, 9007199254740992 + 1得到的值还是9007199254740992

In actual Web development, if you need to pass a Long Int type to Javascript for processing in the background (such as Java), it is very likely that after JavaScript parses the JSON data into the Number type, the result you get is not what you want. Important: The last few digits have changed.

JavaScript uses floating point values ​​for operations, so there will be precision issues in the decimal part, just like all other programming languages ​​that use the IEEE 754 standard format to represent floating point numbers. Avoid equality judgments on decimal parts in your code. (The integer part is precise)

var a = 0.1;
var b = 0.2;
alert(a + b === 0.3); // false

If the value exceeds the upper limit of the number that JavaScript can represent (overflow), it will be automatically converted to an Infinity (or -Infinity, negative infinity) value representing infinity; if the value Infinitely close to 0 and exceeding the JavaScript representation range (underflow), it will be set to 0 (or -0, the same as 0). JavaScript will not cause overflow errors (including when dividing by zero).

var a = Number.MAX_VALUE * 2;          //Infinity
var b = Number.MIN_VALUE / 2;          //0
var c = 1 / 0;                         //Infinity or NaN, 依JS执行环境不同
var d = 0 / 0;                         // NaN

The Number type defines a special value NaN, which is not-a-number. The meaning of NaN means that no value is obtained where a value should be obtained. Any arithmetic operation that uses NaN as an operand will result in NaN.

另外NaN也是唯一一个使用对自身进行相等判断会得到false的数值。NaN的这个怪异之处破坏了JavaScript运算符的对称性。如果在代码中需要通过比较数值大小进行分支判断,就需要注意可能出现NaN的情况,因为使用NaN与其他数值进行大小比较总会得到false,而这可能不是你想要的结果。

var a = 10;   
a = a - "not number"         // NaN
alert(a === a);             // false
var b = 12 + a;              // NaN
var c = 10;
alert(b >= c || b < c);      // false

另一个Number类型中不常引人注目的地方是位运算。JavaScript中提供了按位操作运算符。在很多其他编程语言中,按位操作可以进行硬件级处理,所以非常快。

但是JavaScript没有整数类型,它的位操作是先把数值转换为32位整数,然后进行计算,然后再转换回去,JavaScript绝大部分运行环境是在浏览器中,与硬件相隔较远,因此位操作执行很慢。

3、字符串

与很多其他编程语言中一样,JavaScript中的字符串值也是不可变的,改变一个字符串变量的值,相当于重新生成了一个字符串并把它赋值给变量。JavaScript中的简单类型无法进行方法调用(作为this调用函数),但我们还是可以进行诸如

"abcdefg".toUpperCase();

这样的操作。这是因为JavaScript为简单数据类型提供了一种方式,把它们包装为对象类型,然后进行方法调用。”"abcdefg"“先被隐式地包装为对象,然后使用包装出的对象调用toUpperCase方法,待方法调用结束后,JavaScript再隐式地把包装对象回收。

其它简单数据类型也使用同样的方式。也可以使用JavaScript提供的构造函数显示地创建包装对象,JavaScript提供了String()、Number()和Boolean()三个构造函数,分别用于构建String、Number和Boolean类型的包装对象。

4、类型转换

ECMA-262中对数据类型的转换有详细的定义,很多JavaScript的参考资料也会列出类型转换的详细规则,这里就不再赘述了,下面只讨论一些值得注意的问题。

JavaScript有两组相等比较运算符:”===“和”!==“、”==“和”!=“。Crockford在著作《JavaScript:The Good Parts》里面列举的Bad Parts中的第一个就是”==“运算符。

原因在于”==“运算符会执行隐式的类型转换,而JavaScript中类型转换的规则又非常复杂,很容易导致代码中出现不易发现的bug。与”===“和其他编程语言中的”==“不同,JavaScript中的”==“运算符并不具备传递性: ∀x∀y∀z(x == y ∧ y == z → x == z)并不成立:

"" == "0";             // false
"" == 0;               // true
"0" == 0;              // true

Crockford和Zakas都建议不要使用“==”运算符,而使用“===”代替。若不遵循这个建议,使用“==”运算符时,请务必确保你明确知道两个比较变量的类型信息,以免发生预料之外的类型转换。

另外一个经常用到类型转换的地方是分支判断。if(和其它)语句并不要求进行分支判断的表达式结果必须为Boolean类型,而会根据特定的规则把判断表达式的结果转换为true或false后再进行判断。

if (obj !== undefined && obj !== null) {
    // code
}

// 上面的判断条件可以替换为

if (obj) {
    // code
}

上面代码中的obj代表一个对象变量,若其值为undefined或null,则被转换为false,反之转换为true。这种方式并不完全安全,若使用的变量是简单数据类型,就需要注意一些特殊值的转换规则,否则代码可能不会按照预想的方式执行。

if (typeof num === "number" && num) { 
    // if num is 0, get false
    //code
}

上面代码的本意是获取一个有效的数值类型,屏蔽了其他类型和num的值为NaN的情况(NaN会转换false)。但代码中有一个纰漏,它忽略了num值为0的情况。

0值会被转换为false,从而导致下面的代码不会被执行,这可能与编码者的本意相违背。同样使用String类型作为分支条件,也要考虑""会被自动转换为false的情况。

与分支判断中的类型转换相似的情况,是采用短路方式为变量赋值。由于JavaScript中”&&“和”||“操作符的特性,我们经常采用短路方式为变量赋值。

”&&“操作符会返回表达式中第一个可以转换为false的操作数或最后一个操作数(全为true时);”||“操作符返回表达式中第一个可以转换为true的操作数或最后一个操作数(全为false时)。

var obj = obj1 || obj2 || {}; 
var attr = obj && pro && attr;

与分支判断一样,需要警惕表达式中可能出现的特殊值:0,"",null等。

JavaScript的类型模型,提供了极大的灵活性的同时也带来了很多陷阱,编码过程中需要小心地规避这些陷阱,因为代码审查很容易忽略它们,出现问题时,它们也往往很难被发现。

更多计算机编程相关知识,请访问:编程入门!!

The above is the detailed content of A deeper understanding of primitive types in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:oschina.net. If there is any infringement, please contact admin@php.cn delete