Front-end development - JavaScript data types and reference types


Poetry and distance, drunk dream Huangliang

After all, I gave up the old rice and the chaff


——Lungcen

Table of contents

JS variable definition and assignment

var keyword (global variable)

let (local variable) and const (constant)

JS data type

typeof operator

JS primitive data types

String type

Number type

Boolean type

Null type

Undefined type

   Symbol type

Implicit conversions of various types

JS reference data type

Object type

Array type

Function type

JS output

alert() function

confirm() function

console.log()

document.write()

innerHTML



JS variable definition and assignment


In JavaScript, variable names cannot be defined casually, and need to follow the naming rules of identifiers:

  • Variable names can contain numbers, letters, underscores _, and dollar signs $;

  • Chinese characters cannot appear in variable names ;

  • Variable names cannot contain spaces ;

  • Variable names cannot be keywords or reserved words in JavaScript ;

  • Variable names cannot start with a number, i.e. the first character cannot be a number .

When the variable name contains multiple English words, it is recommended to use camel case:

Big hump : the first letter of each word is capitalized, such as FileType, DataArr

Small camel case : the first letter of the first word is lowercase, and the first letter of the word after the first letter is capitalized, such as fileType, dataArr

var keyword (global variable)

var num = 1;

The var variable can undergo variable promotion , that is, the declared variable will be promoted to the head of the code

    <script>
        document.write(str); //显示undefined
        var str = "hhh";
        document.write(str); //显示 hhh
    </script>

In the above example, the definition of str is after the first line. Logically speaking, the first line should report an error indicating that no variable is defined, but since var can have variable promotion, the first line shows that it is undefined (which can be understood as unassigned) .

let (local variable) and const (constant)

Before 2015, JavaScript could only declare variables through the var keyword. After the release of ECMAScript6 (ES6), two new keywords, let and const, were added to declare variables.

Variables declared with the let keyword are only valid in the code block where they are located ( similar to local variables ), and in this code block, variables with the same name cannot be declared repeatedly;

The function of the const keyword is the same as that of let, but the variable declared with the const keyword has another feature, that is, the variable defined with the const keyword cannot be modified once it is defined (that is, the variable defined with the const keyword is a constant )


JS data type


JavaScript is a weak language with dynamic types. It is not necessary to specify the type of the variable in advance when defining the variable. The type of the variable is dynamically determined by the JavaScript engine during the running of the program, so the same variable can be used to store different types of data.

Data types in JavaScript can be divided into two types:

  • Basic data types (value types): String (String), Number (Number), Boolean (Boolean), Null (Null), Undefined (Undefined), Symbol (new);

  • Reference data types: Object (Object), Array (Array), Function (Function).

typeof operator

When you don't know the type of the data, you can use typeof to return the data type of the variable . The typeof operator has two usages with and without parentheses

typeof x;       // 获取变量 x 的数据类型
typeof(x);      // 获取变量 x 的数据类型

JS primitive data types

String type

String (String) type is a piece of text wrapped in single quotes ''or double quotes""

var str1 = "Hello"
var str2 = new String("Hello")

Strings are converted to numeric values . Since there are two numeric types, there are two ways to convert strings to numeric values. It should be noted that only strings that are pure numeric values ​​can be converted, otherwise an error will be reported

parseInt can be converted to int. If the parameter is a decimal, the decimal part is omitted directly.

parseFloat can be converted to float

var str1 = "110.011"
    var str2 = parseInt(str1)
    var str3 = parseFloat(str1)
    console.log(str2)
    console.log(str3)

Some methods in the string can convert case :

Convert uppercase to lowercase: str1.toLowerCase()

Convert lowercase to uppercase: str1.toUpperCase()

var str1 = "abcABC"
    console.log(str1.toUpperCase())
    console.log(str1.toLowerCase())

Get the occurrence position of the string of the desired target , the parameter of the method can be a character or a string:

Get the position where the string appears for the first time: str1.indexOf("a")

Get the position of the last occurrence of the string: str1.lastIndexOf("a")

var str1 = "abcABCabcABCabcABC"
    console.log(str1.indexOf("a"))
    console.log(str1.lastIndexOf("a"))

Split the string , split() , the parameter inside is the delimiter, the method can split the string according to your delimiter

    var str1 = "abc_ABC_abc_ABC_abc_ABC"
    var str2 = str1.split("_")
    console.log(str2)

Number type

The Number type is used to define a value. In JavaScript, integers and decimals (floating point numbers) are not distinguished , and the Number type is used to represent them uniformly. However, the values ​​​​that Number can define are not unlimited .

The bottom layer of JavaScript is all floating point numbers, which will be automatically converted to decimals or integers during use

There are also some special values ​​in the Number type, namely Infinity, -Infinity and NaN, among which

  • Infinity: used to represent the value of positive infinity, generally refers to the number greater than 1.7976931348623157e+308;

  • -Infinity: used to represent the value of negative infinity, generally refers to the number less than 5e-324;

  • NaN: Not a value (abbreviation for Not a Number), used to represent an invalid or undefined mathematical operation structure, such as dividing 0 by 0.

  • isNaN(x), which means to judge whether it is a non-numeric value. The return value is true or false

Boolean type

The Boolean type has only two values, true (true) or false (false), and some expressions can also be used to get the value of the Boolean type

Null type

Null is a special data type with only one value, which represents an "empty" value, that is, there is no value, nothing, and is used to define a null object pointer.

Use the typeof operator to view the type of Null, and you will find that the type of Null is Object, indicating that Null actually uses a special value belonging to Object (object). So by assigning a variable to Null we can create an empty object.

Undefined type

Undefined is also a special data type with only one value, representing undefined. When we declare a variable but do not assign a value to the variable, the default value of this variable is Undefined

When you use the typeof operator to view unassigned variable types, you will find that their types are also undefined

For undeclared variables, use the typeof operator to view their types and you will find that undeclared variables are also undefined

   Symbol type

Symbol is a new data type introduced in ECMAScript6, which represents a unique value , and the value of Symbol type needs to be generated using the Symbol() function

Implicit conversions of various types

 1. Value type

        Convert string: direct conversion. For example: var s = "abc" + 18, the input s is: "abc18"

        Turn Boolean value: 0 and NaN turn false, others turn true

2. Boolean type

        Convert string: direct conversion. similar value to string

        Rotation value: true is 1, false is 0

3. String type

        Turning value: turn it if it can, and turn it to NaN if it can't. The result of any operation with a numeric value and NaN is NaN

        Turn Boolean value: empty string is false, others are true

4. To define the type

        Convert string: direct conversion

        Turn Boolean: false

        Revolution value: NaN

5、null

        Convert string: direct conversion

        Turn Boolean: false

        Revolution value: 0


JS reference data type


Object type

The object (Object) type in JavaScript is an unordered set of keys and values . Curly braces are required to define the object type{ }


var date = new Date Date is a built-in method

var obj = new Object

object.name = "Zhang San" does not have to be name, it can be other


{name1: value1, name2: value2, name3: value3, ..., nameN: valueN}

var datas = [{name: '贾静雯', subject: 'JavaScript', score: 100}, 
             {name: '赵敏', subject: 'HTML', score: 98}, 
             {name: '贾静雯', subject: 'CSS', score: 99}];
获取某一行:datas[i]
获取某一个:datas[i]["value"]  value 对应就是 name 或者 subject 或者 score
var person = {name: 'Bob', age: 20, tags: ['js', 'web', 'mobile'],
    city: 'Beijing', hasCar: true, zipcode: null };

console.log(person.name);       // 输出 Bob
console.log(person.age);        // 输出 20

The keys of the object type are all string types, and the values ​​can be of any data type. To get a value in an object, you can use  the form 对象名.键 

Array type

Array (Array) is a collection of data arranged in order . Each value in the array is called an element, and the array can contain any type of data. To define an array in JavaScript, you need to use square brackets [ ], and each element in the array is separated by a comma

[1, 2, 3, 'hello', true, null]
var arr = new Array(1, 2, 3, 4);

Elements in an array can be accessed by index. The index in the array starts from 0 and increases sequentially, that is to say, the index of the first element of the array is 0, the index of the second element is 1, the index of the third element is 2, and so on

Function type

Function (Function) is a block of code with a specific function, the function will not run automatically, it needs to be called by the function name to run

function sayHello(name){
    return "Hello, " + name;
}
var res = sayHello("Peter");

JS output

  1. Use the alert() function to pop up a prompt box;

  2. Use the confirm() function to pop up a dialog box;

  3. Use the document.write() method to write the content into the HTML document;

  4. Use innerHTML to write content into HTML tags;

  5. Use console.log() to output content to the browser's console.

alert() function

The alert() function can pop up a prompt box in the browser . In the prompt box, we can define the content to be output. In t(), only text content can be output.

The alert() function is a function under the window object, so sometimes we can call the alert() function in the form of window.alert() for more rigorous code.

confirm() function

The confirm() function is also a function under the window object. It can also pop up a prompt box in the browser window. The difference is that in the prompt box created by using the confirm() function, besides a "OK" button, there is also a "OK" button. Cancel" button . If the "OK" button is clicked, the confirm() function will return a Boolean value true, and if the "Cancel" button is clicked, the confirm() function will return a Boolean value false.

console.log()

console.log() can output information on the console of the browser. To see the output of console.log(), you need to open the console of the browser first.

document.write()

document.write() can write HTML or JavaScript code to the HTML document

innerHTML

innerHTML is an attribute rather than a function, through which you can set or get the content in the specified HTML tag

<body>
    <div id="demo"> JavaScript 输出</div>
</body>   
<script>
    var demo = document.getElementById("demo");
    console.log(demo.innerHTML);
    demo.innerHTML = "<h2>innerHTML</h2>";
</script>

Poetry and distance, drunk dream Huangliang

After all, I gave up the old rice and the chaff


——Lungcen

Guess you like

Origin blog.csdn.net/qq_64552181/article/details/129865331