JavaScript (Notes)

Table of contents

Hello World

JavaScript variables

JavaScript dynamic typing

implicit type conversion

JavaScript array

JavaScript function

Scope of variables in JavaScript

object

DOM

Select page elements

event

Get/modify element content

Get/modify element attributes

Get/modify form element attributes

Get/modify style attributes

Add new element

delete element

Code example:

1. Guess the number in the web version

confession wall program


JS runs on the browser. For example, there is a special module in chrome, which is the JS engine. It is equivalent to the JVM and can interpret and execute js code.

The composition of JS:

DOM API is the API provided by the browser for js to operate the page. 

The BOM API is an API provided by the browser for js to operate the browser window.


Hello World

Embed into html through script tags, three introduction methods:

1. Internal js 

 2. External js 

Write it as a separate .js file and let html be imported.

3. Inline js 

 alert can pop up a window so that the user can see the output of the program, but the pop-up window operation is not very good.

Some dialog boxes, once they pop up, will prevent the user from operating other parts of the interface. They are called modal dialog boxes.

console .log can print the log in the console

 console.log in js is similar to println in java, and is also a very useful debugging method


JavaScript variables

var variable name = initial value

You don’t have to write a type to define a variable in js. Not writing a type doesn’t mean there is no type.

Rather, the type of the variable is determined by the value of the initialization operation.

The keyword used to define variables in js can also be written as let


JavaScript dynamic typing

The type of a variable can change while the program is running . This characteristic is called dynamic characteristics.

If the type of a variable cannot change while the program is running, it is called a static type.

The biggest advantage of dynamic typing is that the code is very flexible

For example, if you write a function to calculate the sum of two numbers, if you use Java, you may have to write two ints to add, two doubles to add, two longs to add... etc.

In a dynamically typed language, you only need to write a function

The disadvantages of dynamic typing are also obvious: it is uncertain what type a variable currently is, what kind of values ​​it stores, and what methods and properties it provides.

Several types built into JavaScript:

In other languages, if something is accessed that is not defined , an error will be reported directly.

However, JS will not report an error, but directly returns undefined. 


implicit type conversion

In this code, implicit type conversion is triggered

In JS, when comparing/operating on different types, it will try to convert them into the same type as much as possible.

Another example:

The final result is also true

Languages ​​like Java that do not support implicit type conversion are called "strongly typed" languages.

Languages ​​like JS that can support implicit type conversion are called "weakly typed" languages.

 In JavaScript, a === is introduced

When comparing using ===, no implicit type conversion is performed


JavaScript array

Both of these are ways to create arrays in JS

But generally the second one is used

In JS, the element types of arrays do not need to be uniform and can be of any type! ! !

This is not only true for JS, but also for dynamically typed languages.

How to operate on array elements?

Working with array subscripts

The array of JS is not just an array in the traditional sense (you can only fetch elements by pressing the subscript), but a thing with the nature of "key-value pairs"

It is better to understand it as a hybrid of Map + array. At this time, the array can also organize data according to the Map key-value pair.

In later versions of JS, a special map is introduced to represent key-value pairs

Array traversal:

1. Use for loop

2. Use for-each

 3. The second type of for-each

Add elements to an array (tail insertion)

Just use push method

Remove elements from an array:

Use the splice method


JavaScript function

Function syntax rules:

 There is no need to write the type in the brackets (any type is fine, as long as the variable you pass in can work normally inside the function)

When we add undefined and 10, the result will be NaN.

The full name is Not a Number, which means: not a number.

However, our code will not report an error. This result does not meet the user's expectations, but it will not report an error.

If the number of actual parameters is less than the number of formal parameters, the value of the extra formal parameters is undefined.

If there are too many formal parameters, the extra formal parameters will be useless.

In short, when the number of formal parameters and actual parameters does not match, no error will be reported, and it will only be executed as much as possible.

Each function will customize an arguments variable, which is an array and contains all actual parameters.

Using arguments, we can add any number of numbers

For dynamically typed languages ​​like JS, there is no need for syntax like "overloading"

Function expression:

First define an anonymous function without a name, and then assign the anonymous function to an add variable.

The type of the add variable is called the function type

Variables of function type can be called

In JS, you can assign a function to a variable in the same sense as a normal variable, and you can also use the function as a parameter of another function, or use the function as the return value of another function (this cannot be done in Java)

This feature is called: functions are "first-class citizens" in JS


Scope of variables in JavaScript

When you want to access a variable in the code, where do you find the variable?

JS will first look for the current scope. If it is not found currently, it will look for it in the upper scope, all the way up to the global scope. If it still cannot find it, it will report an error / undefined

 This syntax setting is similar to variable capture in Java


object

JS is not an object-oriented programming language, but there is the concept of objects

This means that the setting of objects in JS is very different from that in JAVA.

There is no encapsulation, inheritance, polymorphism, or even classes in js

js objects have properties and methods (methods are essentially properties, because functions are first-class citizens in js)

Here, the object of js is formed

We can also create objects using Object

What attributes and methods there are in the js object are not agreed in advance and can be added at any time.


DOM

DOM: Document Object Model, each tag in html can be mapped to a corresponding object in js

Whatever is displayed on the label can be perceived through the js object

js object modifies the corresponding attributes, which can affect the display of labels

Through dom, js code can be used to operate page elements.

There are many APIs for DOM. We only introduce a few commonly used APIs here.

Select page elements

querySelector (CSS selector)

Document is a global object in the browser. Any page will have a document object.

All DOM APIs are expanded through document objects  

If there are multiple boxes, the default is the first one.

If you want to select them all, there is another method: querySelectorAll() (returns an array) 


event

Events are responses to user operations.

To be able to interact with the user, you need to know what the user has done. Some actions the user takes will generate some events in the browser.

The code needs to react to events

Three elements of the event:

1. Event source: which element generated the event

2. Event type: click, double-click, move, press

3. Event handler: After the event occurs, which code should be executed (the codes to be executed are all set in advance)

In the front-end page, there are also different handling methods for events, which are all set from the beginning.

The simplest way: directly use the on XXX method in the element to bind an event handler

Event source: .box Event type: onlick Event handler: alert


Get/modify element content

First get the element and use the innerHTML attribute to get the content in the element.

Modifying this property will affect the display of the interface


Get/modify element attributes

The attributes of the html tag will also be mapped to the js object


Get/modify form element attributes

Form elements (input, textarea, select...) have some special attributes that ordinary tags do not have.

value gets the value filled in by the user in the element

Put a number into the input, and each time the button is clicked, the number +1 will be displayed.

The value attribute is a String. Just +1 will turn it into a string. We need to use parseInt to convert the string into an integer.


Get/modify style attributes

1. Directly modify the content style

(Modify the value of the style attribute)

Create a div that will enlarge the font every time you click it

The attribute names in style are the same as those in CSS, except that the spine naming is replaced by camel case. 

2. Modify the CSS class name applied to the element

Switch to night mode


Add new element

1. Create an element

2. Put this element into the dom

Use the createElement method to create elements


delete element

parentElem.removeChild


Code example:

1. Guess the number in the web version

1. Generate a random number between 1 and 100

2. Let the user enter a number

3. Give prompts based on the size relationship of numerical input

Use Math.random to generate a random number between [0,1)

Set the random number to N, based on this *100, at this time the range of N is [0,100)

And use parseInt to remove the decimal part, and finally get an integer between [0,100)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>猜数字</title>
</head>
<body>
    <div>请输入要猜的数字</div>
    <input type="text">
    <button>提交</button>
    <!-- 使用这个 div 来显示结果 -->
    <div class="result">

    </div>
    <script>
        //1、先生成一个随机的整数
        let toGuess = parseInt(Math.random() * 100) + 1;
        console.log(toGuess);
        //2、进行猜数字操作
        let button = document.querySelector('button');
        let input = document.querySelector('input');
        let resultDiv = document.querySelector('.result');
        button.onclick = function(){
            //取出输入框里的数字
            if(input.value == ''){
                //用户什么都没有输入
                return;
            }
            let inputNum = parseInt(input.value);
            //4、比较大小关系
            if(inputNum < toGuess){
                //低了
                resultDiv.innerHTML = '低了'
            }else if(inputNum > toGuess){
                //高了
                resultDiv.innerHTML = '高了'
            }else{
                //猜对了
                resultDiv.innerHTML = '猜对了'
            }
        }

    </script>
</body>
</html>

confession wall program

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表白墙</title>
    <style>
        /*  * 是通配符选择器,是选中也米娜所有元素 */
        *{
            /* 消除浏览器的默认样式 */
            margin:0;
            padding:0;
            box-sizing: border-box;
        }
        .container{
            width:600px;
            margin:20px auto;
        }

        h1{
            text-align: center;
        }
        p{
            text-align: center;
            color:#666;
            margin: 20px;
        }
        .row{
            /* 开启弹性布局 */
            display:flex;
            height:40px;
            /* 水平方向居中 */
            justify-content: center;
            /* 垂直方向居中 */
            align-items: center;
        }
        .row span{
            width:100px;
        }
        .row input{
            height:30px;
            width:200px;
        }
        .row button{
            width: 300px;
            height:30px;
            color:white;
            background-color: orange;
            border: none;
            border-radius: 5px;
        }
        /* 点击的时候有反馈 */
        .row button:active{
            background-color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>表白墙</h1>
        <p>输入内容后点击提交,会将信息显示到表格中</p>
        <div class="row">
            <span>谁:</span>
            <input type="text">
        </div>

        <div class="row">
            <span>对谁:</span>
            <input type="text">
        </div>

        <div class="row">
            <span>说:</span>
            <input type="text">
        </div>
        <div class="row">
            <button>提交</button>
        </div>
    </div>

    <script>
        // 实现提交操作
        //点击提交,就能够把用户输入的内容提交到页面上显示
        //在点击的时候,获取到三个输入框的文本内容
        //创建一个新的 div .row ,把文本内容构造到这个 div 中
        let containerDiv  = document.querySelector('.container');
        let inputs = document.querySelector('input');
        let button = document.querySelector('button');
        button.onlick = function(){
            //1、获取到三个输入框的内容
            let from = inputs[0].value;
            let to = inputs[1].value;
            let msg = inputs[2].value;
            if(from == '' || to == '' || msg == ''){
                return;
            }

            //构造新的 div
            let rowDiv = document.createElement('div');
            rowDiv.className = 'row';
            rowDiv.innerHTML = from + ' 对 ' + to + ' 说: ' + msg;
            containerDiv.appendChild(rowDiv);
            //清空之前的输入框内容
            for(let input of inputs){
                input.value = '';
            }
        }
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_73616913/article/details/132380263