Data types
The following data types are defined in JavaScript:
Number
JavaScript does not distinguish between integers and floating point numbers, and is represented by Number. The following are legal Number types:
123; // 整数123 0.456; // 浮点数0.456 1.2345e3; // 科学计数法表示1.2345x1000,等同于1234.5 -99; // 负数 NaN; // NaN表示Not a Number,当无法计算结果时用NaN表示
Infinity; // Infinity means infinite. When the value exceeds the maximum value that can be represented by JavaScript's Number, it is expressed as Infinity
Since computers use binary, it is sometimes more convenient to use hexadecimal to represent integers. Hexadecimal Represented by 0x prefix and 0-9, a-f, for example: 0xff00, 0xa5b4c3d2, etc. They are exactly the same as the values expressed in decimal.
Number can directly perform four arithmetic operations, and the rules are consistent with mathematics:
1 + 2; // 3 (1 + 2) * 5 / 2; // 7.5 2 / 0; // Infinity 0 / 0; // NaN 10 % 3; // 1 10.5 % 3; // 1.5
Note that % is the remainder operation.
String
A string is any text enclosed in single quotes ' or double quotes ", such as 'abc', "xyz "And so on. Please note that '' or "" itself is just a way of expression, not part of the string. Therefore, the string 'abc' only has 3 characters a, b, c.
Boolean value
The representation of Boolean value and Boolean algebra is exactly the same. A Boolean value has only two values: true and false. Either true or false. You can use true or false directly. false represents a Boolean value, which can also be calculated through Boolean operations:
true; // 这是一个true值 false; // 这是一个false值 2 > 1; // 这是一个true值 2 >= 3; // 这是一个false值
&& operation is an AND operation. Only when everything is true, the result of && operation is true. :
true && true; // 这个&&语句计算结果为true true && false; // 这个&&语句计算结果为false false && true && false; // 这个&&语句计算结果为false
|| operation is an OR operation, as long as one of them is true, the || operation result is true:
false || false; // 这个||语句计算结果为false true || false; // 这个||语句计算结果为true false || true || false; // 这个||语句计算结果为true
! The operation is a non-operation, which is a unary operator that turns true into false and false into true:
##
! true; // 结果为false ! false; // 结果为true ! (2 > 5); // 结果为true
var age = 15; if (age >= 18) { alert('adult'); } else { alert('teenager'); }
Comparison operators
2 > 5; // false 5 >= 2; // true 7 == 7; // true
##
false == 0; // true false === 0; // false
One is == comparison, which will automatically convert data types before comparison. In many cases, very strange results will be obtained;
Due to this design flaw in JavaScript, do not use == comparison, always stick to === comparison
Another exception is the special Number NaN that is different from all other values. Not equal, including itself:
NaN === NaN; // false
isNaN(NaN); // true
1 / 3 === (1 - 2 / 3); // false
This is not a design flaw of JavaScript. Floating point numbers will be affected during the operation. Errors occur because computers cannot accurately represent infinite recurring decimals. To compare whether two floating point numbers are equal, you can only calculate the absolute value of their difference to see if it is less than a certain threshold:
##
Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // true
null and undefined
null represents an "empty" value, which is different from 0 and the empty string'', 0 is a numerical value, '' represents a string of length 0, while null represents "empty". In other languages, there are also representations of null similar to JavaScript. For example, Java also uses null, Swift uses nil, and Python uses None. However, in JavaScript, there is also undefined, which is similar to null, which means "undefined".
The designers of JavaScript hope to use null to represent an empty value, and undefined to represent an undefined value. Facts have proved that this is of no use, and the difference between the two is of little significance. In most cases, we should use null. undefined is only useful when determining whether function parameters are passed. ArrayAn array is a set arranged in order, and each value of the set is called an element. JavaScript arrays can contain any data type. For example:
[1, 2, 3.14, 'Hello', null, true];
Another way to create an array is through the Array() function:
new Array(1, 2, 3); // 创建了数组[1, 2, 3]
Elements of an array can be accessed by index. Note that the index starts at 0:
##
var arr = [1, 2, 3.14, 'Hello', null, true]; arr[0]; // 返回索引为0的元素,即1 arr[5]; // 返回索引为5的元素,即true arr[6]; // 索引超出了范围,返回undefined
JavaScript’s object is An unordered set of key-value pairs, for example:
var person = { name: 'Bob', age: 20, tags: ['js', 'web', 'mobile'], city: 'Beijing', hasCar: true, zipcode: null };
JavaScript对象的键都是字符串类型,值可以是任意数据类型。上述person对象一共定义了6个键值对,其中每个键又称为对象的属性,例如,person的name属性为'Bob',zipcode属性为null。
要获取一个对象的属性,我们用对象变量.属性名的方式:
person.name; // 'Bob' person.zipcode; // null
变量
变量的概念基本上和初中代数的方程变量是一致的,只是在计算机程序中,变量不仅可以是数字,还可以是任意数据类型。
变量在JavaScript中就是用一个变量名表示,变量名是大小写英文、数字、$和_的组合,且不能用数字开头。变量名也不能是JavaScript的关键字,如if、while等。申明一个变量用var语句,比如:
var a; // 申明了变量a,此时a的值为undefined var $b = 1; // 申明了变量$b,同时给$b赋值,此时$b的值为1 var s_007 = '007'; // s_007是一个字符串 var Answer = true; // Answer是一个布尔值true var t = null; // t的值是null
变量名也可以用中文,但是,请不要给自己找麻烦。
在JavaScript中,使用等号=对变量进行赋值。可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量,但是要注意只能用var申明一次,例如:
var a = 123; // a的值是整数123 a = 'ABC'; // a变为字符串
这种变量本身类型不固定的语言称之为动态语言,与之对应的是静态语言。静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。例如Java是静态语言,赋值语句如下:
int a = 123; // a是整数类型变量,类型用int申明 a = "ABC"; // 错误:不能把字符串赋给整型变量
和静态语言相比,动态语言更灵活,就是这个原因。
请不要把赋值语句的等号等同于数学的等号。比如下面的代码:
var x = 10; x = x + 2;
如果从数学上理解x = x + 2那无论如何是不成立的,在程序中,赋值语句先计算右侧的表达式x + 2,得到结果12,再赋给变量x。由于x之前的值是10,重新赋值后,x的值变成12。
strict模式
JavaScript在设计之初,为了方便初学者学习,并不强制要求用var申明变量。这个设计错误带来了严重的后果:如果一个变量没有通过var申明就被使用,那么该变量就自动被申明为全局变量:
i = 10; // i现在是全局变量
在同一个页面的不同的JavaScript文件中,如果都不用var申明,恰好都使用了变量i,将造成变量i互相影响,产生难以调试的错误结果。
使用var申明的变量则不是全局变量,它的范围被限制在该变量被申明的函数体内(函数的概念将稍后讲解),同名变量在不同的函数体内互不冲突。
为了修补JavaScript这一严重设计缺陷,ECMA在后续规范中推出了strict模式,在strict模式下运行的JavaScript代码,强制通过var申明变量,未使用var申明变量就使用的,将导致运行错误。
启用strict模式的方法是在JavaScript代码的第一行写上:
'use strict';
这是一个字符串,不支持strict模式的浏览器会把它当做一个字符串语句执行,支持strict模式的浏览器将开启strict模式运行JavaScript。
来测试一下你窗体顶端
'use strict'; // 如果浏览器支持strict模式, // 下面的代码将报ReferenceError错误:
数据类型如何转换:
1. Convert to number xxx*1.0
Convert to string xxx+""
2. Extract another type of value from one value and complete the conversion work.
.Extract the integer from the string: parseInt();
Example: the result of parseInt("123zhang") is 123
.Extract the floating point number from the string: parseFloat();
Example : The result of parseFloat("0.55zhang") is 0.55
. Execute a piece of javascript code represented by a string: eval();
Example: the result of zhang=eval("1+1") is zhang=2
. Convert to string: toString();
Example: zhang=eval("1+1") results in zhang=2
3. Convert the entire value from one type to another A data type (called basic data type conversion),
Three methods of basic data type conversion:
. Convert to character type: String(); Example: The result of String(678) is "678"
. Convert to numeric type: Number(); Example: The result of Number("678") is 678
. Convert to Boolean type: Boolean(); Example: The result of Boolean("aaa") is true
When using these methods, if necessary, try to judge and handle exceptions on the execution of parameters and methods.
As seen in the reference document, the following is a summary of execution efficiency:
Under IE, the first type is the fastest, the second type is second, and the third type is the worst, but the difference is only 100,000 times , the difference is only tens of hundreds of milliseconds.
Under FF, the first and second types are basically equivalent, and the third type is the slowest.
The speed difference can basically be ignored. Because the difference is very small.
However, from the simplicity of the code, the first method is obviously simple to write and easy to read.
And the second method will not cause an error because an object does not have a toString method. Besides, he was always the fastest.
So, I am used to using the first method to complete data type conversion
However, for example, if you need "123456abcd" to extract the numbers, then you should naturally use functions such as parsetInt and parseFloat.
But please note that sometimes the conversion result is NaN, etc., which needs to be judged.
The above is the detailed content of What are JavaScript data types and variables? How to convert between them?. For more information, please follow other related articles on the PHP Chinese website!