Data types and variables

Data Type

As the name suggests, a computer is a machine that can do mathematical calculations. Therefore, computer programs can naturally handle various numerical values. However, computers can process much more than just numerical values. They can also process a variety of data such as text, graphics, audio, video, web pages, etc. Different data require the definition of different 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; // Integer 1230.456; // Floating point number 0.4561.2345e3; // Scientific notation represents 1.2345x1000, which is equivalent to 1234.5-99; // Negative number NaN; // NaN represents Not a Number, When the result cannot be calculated, use NaN to represent Infinity; // Infinity represents infinity. When the value exceeds the maximum value that JavaScript's Number can represent, it is represented as Infinity

Since computers use binary, Therefore, sometimes it is more convenient to use hexadecimal to represent integers. Hexadecimal is represented by the 0x prefix and 0-9, a-f, for example: 0xff00, 0xa5b4c3d2, etc. They are exactly the same as the values ​​represented by decimal.

Number can directly perform four arithmetic operations. The rules are consistent with mathematics:

1 + 2; // 3(1 + 2) * 5 / 2; // 7.52 / 0; // Infinity0 / 0; // NaN10 % 3; // 110.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", etc. Please note , '' or "" itself is just a representation, not part of the string. Therefore, the string 'abc' only has 3 characters: a, b, c.

Boolean value##.

#The representation of Boolean values ​​and Boolean algebra is exactly the same. A Boolean value has only two values: true and false, either true or false. You can directly use true or false to represent a Boolean value, or you can use Boolean The operation is calculated:

true; // This is a true value false; // This is a false value 2 > 1; // This is a true value 2 >= 3; // This is A false value


&& operation is an AND operation. Only when everything is true, the result of && operation is true:

true && true; // The result of this && statement is truetrue && false; // This && statement evaluates to false false && true && false; // This && statement evaluates to false


|| The operation is an OR operation, as long as one of them is true, | |The result of the operation is true:

false || false; // This || statement evaluates to falsetrue || false; // This || statement evaluates to truefalse || true || false; // This || statement evaluates to true


!The operation is a non-operation. It is a unary operator that turns true into false and false into true:

! true; // The result is false! false; // The result is true! (2 > 5); // The result is true

Boolean values ​​are often used in conditional judgments, such as:

var age = 15;if (age >= 18) {
    alert('adult');
} else {
    alert('teenager');
}

Comparison operator

When we compare Number, we can get a Boolean value through the comparison operator:

2 > 5; // false5 >= 2; // true7 == 7; // true

In fact, JavaScript allows comparison of any data type:

false == 0; // truefalse === 0; // false

Be special Note the equality operator ==. When JavaScript is designed, there are two comparison operators:

The first one is == comparison, which will automatically convert the data type and then compare. In many cases, very strange results will be obtained;

The second type is === comparison, which does not automatically convert data types. If the data types are inconsistent, false is returned. If they are consistent, compare again.

Due to this design flaw in JavaScript, do not use == comparisons and always stick to === comparisons.

Another exception is NaN. This special Number is not equal to all other values, including itself:

NaN === NaN; // false

The only way to determine NaN is through the isNaN() function:

isNaN(NaN); // true

Finally, pay attention to the equality comparison of floating point numbers:

1 / 3 === (1 - 2 / 3); // false

This is not a design flaw in JavaScript. Floating point numbers produce errors during operations because computers cannot accurately represent infinitely 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, and 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.

Array

An 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];

The above array contains 6 elements. Arrays are represented by [], and elements are separated by ,.

Another way to create an array is through the Array() function:

new Array(1, 2, 3); // Created array [1, 2, 3]


However, for the sake of code readability, it is strongly recommended to use [] directly.

The elements of an array can be accessed by index. Please note that the starting value of the index is 0:

var arr = [1, 2, 3.14, 'Hello', null, true];
arr[0]; // 返回索引为0的元素,即1arr[5]; // 返回索引为5的元素,即truearr[6]; // 索引超出了范围,返回undefined

Object

JavaScript object is an unordered collection of key-values, for example:

var person = {
    name: 'Bob',
    age: 20,
    tags: ['js', 'web', 'mobile'],
    city: 'Beijing',
    hasCar: true,
    zipcode: null};

The keys of JavaScript objects are all string types, and the values ​​can be of any data type. The above person object defines a total of 6 key-value pairs, each of which is also called an attribute of the object. For example, the name attribute of person is 'Bob' and the zipcode attribute is null.

To get the properties of an object, we use the object variable.property name method:

person.name; // 'Bob'person.zipcode; // null

Variables

The concept of variables is basically the same as the equation variables in junior high school algebra. However, in computer programs, variables can not only be numbers, but also can be any data type. .

Variables are represented by a variable name in JavaScript. The variable name is a combination of uppercase and lowercase English, numbers, $, and _, and cannot start with a number. Variable names cannot be JavaScript keywords, such as if, while, etc. To declare a variable, use the var statement, for example:

var a; // Variable a is declared, and the value of a is undefinedvar $b = 1; // Variable $b is declared, and $b is assigned a value at the same time , at this time the value of $b is 1var s_007 = '007'; // s_007 is a string var Answer = true; // Answer is a Boolean value truevar t = null; // The value of t is null

Variable names can also be in Chinese, but please don’t cause trouble for yourself.

In JavaScript, use the equal sign = to assign a value to a variable. Any data type can be assigned to a variable. The same variable can be assigned repeatedly, and it can be a variable of different types. However, it should be noted that it can only be declared once with var, for example:

var a = 123; // a的值是整数123a = 'ABC'; // a变为字符串

The type of this variable itself is not fixed. The language is called a dynamic language, and its counterpart is a static language. In static languages, the variable type must be specified when defining a variable. If the type does not match when assigning a value, an error will be reported. For example, Java is a static language, and the assignment statement is as follows:

int a = 123; // a is an integer type variable, and the type is declared with int a = "ABC"; // Error: cannot assign a string to an integer Type variable

Compared with static language, dynamic language is more flexible, this is the reason.

Please do not equate the equal sign of the assignment statement with the mathematical equal sign. For example, the following code:

var x = 10;
x = x + 2;

If you understand x = x + 2 mathematically, it is not true anyway. In the program, the assignment statement first calculates the expression x + 2 on the right side and gets the result 12. Then assign it to variable x. Since the previous value of x was 10, after reassignment, the value of x becomes 12.

strict mode

At the beginning of JavaScript design, in order to facilitate beginners to learn, it was not mandatory to use var to declare variables. This design error has serious consequences: if a variable is used without var declaration, then the variable is automatically declared as a global variable:

i = 10; // i现在是全局变量

In different JavaScript files on the same page, If no var declaration is used and both variables i happen to be used, the variables i will affect each other and produce erroneous results that are difficult to debug.

A variable declared using var is not a global variable. Its scope is limited to the function body in which the variable is declared (the concept of function will be explained later). Variables with the same name do not conflict with each other in different function bodies.

In order to fix this serious design flaw in JavaScript, ECMA introduced strict mode in subsequent specifications. JavaScript code running in strict mode is forced to declare variables through var. If the variable is used without using var to declare the variable, it will lead to running errors. .

The way to enable strict mode is to write in the first line of JavaScript code:

'use strict';

This is a string and is not supported Browsers in strict mode will execute it as a string statement, and browsers that support strict mode will enable strict mode to run JavaScript.

To test whether your browser can support strict mode:

'use strict';
// If the browser supports strict mode,
// The following code A ReferenceError error will be reported:

abc = 'Hello, world';
alert(abc);
<html>
<head>
 <script>
 var age = 15;
 if (age >= 18) {
 alert('adult');
 } else {
 alert('teenager');
 }
 </script>
</head>
<body>
</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> RunJS 演示代码 </title> <script> var ck = function(){ var x = prompt ("输入数据: ", ""); alert(x); } </script> </head> <body> <button onclick="ck();"> 按钮 </button> </body> </html>
submitReset Code