JavaScript Quick Start Manual

First, get acquainted with JavaScript

1 Introduction

JavaScript is a scripting language that runs on the browser, abbreviated as js. It does not need to be manually compiled, and is saved in the form of an ordinary document. The suffix is ​​".js". By issuing commands to the browser, you can achieve dynamic page functions and user interaction

2. Composition

The JavaScript program is composed of statements, statement blocks (multi-line statements are enclosed in "{}", the function is to make the statement sequence execute together), functions, objects, methods, attributes, etc., which are controlled by three basic programs: sequence, selection, and loop. Structure.

3, points to note

";" At the end of each statement can be added or not added
. Variables can be assigned or not assigned when declaring variables.
Strings can use single or double quotes

Second, how to introduce JavaScript files

1. Write directly where needed

The event is implemented by directly binding the event handle (the event handle is to directly add "on" before the event, such as "click" the event handle is "onclick"). In this case, the mouse click event is triggered by the event handle "onclick".

 <input type="button" onclick="alert('直接在事件处理代码中加入JavaScript代码')" value="直接调用JavaScript代码">

2. Script block method (same as CSS inline style sheet)

Exposed in the script block, executed when the page is opened and executed in a
top-down order (this code is executed without events).

 <script type="text/javascript">
        document.write("第一个JavaScript实例")
        alert("第一个JavaScript实例")
    </script>

3. Introduce independent (same CSS external style sheet)

Map the js script file in the required location.
When an external independent js file is introduced, the code in the js file will be executed line by line in order from top to bottom.

<script type="text/javascript" src="../JavaScript文件/demo.js">
        document.write("src是可选属性,如果加上src属性,则script中的代码会被忽视——这行代码不会执行")
    </script>

Three, JavaScript basic syntax

1. Variables in js

Variable declaration

  • java is a strongly typed language
    java exists in the compilation stage, assuming that there is code int: i; then there is a feature in java: the data type of the i variable has been determined in the java program compilation stage, and the data type of the i variable is being compiled The stage is of type int, then this variable is always of type int until the final memory release, and it cannot be changed to other types
  • JavaScript is a weakly-typed language.
    JavaScript does not exist in the compilation stage. A variable can be assigned at will, and any type of value can be assigned. The type of the variable is determined by the type of the assigned value, so the variable declaration uses "var" uniformly
  • For example (how to declare a variable in JavaScript):
 var i=1;(此时变量类型是整型)
 var i=3.14;(此时的变量名是浮点型)
 var i`=‘abc’;(此时变量的类型是字符串)
  • In JS, when a variable is not manually assigned, the system defaults to undefined (undefined here is a specific value instead of a string. Accessing a variable without definition / declaration will report a syntax error: "variable ”Is not defined.

Types of variables

  • undefined
  • number
    includes integers, decimals, positive numbers, negative numbers, not numbers, infinity
  • On both sides of string
    "+", as long as one of them is string, "+" will do string concatenation operation
    . The result of 10/3 = 3.333333 (weakly typed language)
  • boolean
    has only two values, true and false
  • object
  • object subclass
  • NaN
    is a specific value, which means it is not a number "Not a Number", the singular number is of type number
  • Global variables Variables
    declared outside the function body belong to global variables. The declaration period of global variables is:
    declared when the browser is opened, and destroyed when the browser is closed. Try to use them as little as possible, because global variables will always be in the browser's memory and consume Memory space. Can use local variables as much as possible
  • Local variables
    variables declared in the body of the function comprises a function parameter belongs to a local variable
    lifecycle local variables are: memory space, of local variables open when the function begins execution, after the function is executed, a local variable memory space released
    partial The life cycle of the variable is relatively short.
    In a function, if the local variable and the global variable have the same name, the local variable is called using the "proximity principle"; the global variable is called outside the function body (because the local variable has been destroyed at this time )
    When a variable is declared without the var keyword, then no matter where the variable is declared, it is a global variable
//举个例子
function myfun(){
	name = "wangwu"
}
//访问函数
myfun();
alert("name="+name);//name=wangwu

2. Identifiers and keywords in js

  • Identifier naming rules and specifications are implemented in accordance with java
  • The keywords do not need to be memorized

3. Comments in js

  • Single line comment:
//单行注释

/*
多行注释1
多行注释2
*/

4. Functions in JavaScript

1. How the function is defined

  • Equivalent to the method in the Java language, the function is also a piece of code that is deliberately reused. Functions are generally deliberately complete a specific function
  • Because it is a weakly typed language, there is no need to specify the return value type, whatever class is returned
  • There are two ways to define functions
第一种方式:
	function 函数名(形式参数列表){
				函数体;
		}
第二种方式:
	函数名 = function (形式参数列表){
				函数体;
		}
//其中,形式参数可以由也可以没有
//可以传指定的参数个数,也可以不传指定的参数个数
  • The function must be called to execute the
    calling method:
函数名(实际参数);
  • There is no overloading mechanism for functions in js
  • In java,
    overloading relies on the difference in parameter type and number to achieve overloading
  • In js,
    js is a weakly typed language. The type of the function parameter is not artificially defined, but determined by the type of the parameter itself, so it cannot distinguish different functions by the number and type of parameters like Java Implement overloading
    If two functions have the same name, the function behind will overwrite the function above

2. Special operators and functions

Warning box

  • usage
  • alert (massage), used to enter warning information

Prompt box

  • usage
  • confirm (massage), used to let the user confirm the operation

Confirmation box

  • prompt ("prompt information", "default"), used to display confirmation information
//示例
<!--三种消息对话框-->
    <script type="text/javascript">
        //alter(massage)
        alert("这是警告框,用于输出警告信息")

        function show_confirm(){
            //confirm(massage)
            var tf=confirm("请选择确认按钮!")
            if(tf==true){
                alert("您按了确认按钮")
            }else{
                alert("您按了取消按钮!")
            }
        }

        function disp_confirm(){
           //prompt("提示信息","默认值");
             var name=prompt("请输入您的姓名","李大为");
            if(name!=null && name!=""){
                document.write("您好",+"name")
            }
        }
       
    </script>

    <form action="" method="POST">
        <input type="button" onclick="show_confirm()" value="显示确认框"/>
        <input type="button" onclick="disp_confirm()" value="显示提示框"/>
    </form>

typoof operator

  • usage
  • alert (typeof variable name), you can dynamically get the data type of the variable during the program running phase
- 运算结果是以下6个字符串之一
 “undefined”
 “number”
 “string”
 “boolean”
 “object”
 “function”
//例子
var v1 = 1;
alert(typeof v)//"number"

var v2 = "abc";
alert(typeof v)//"string"

"==" equivalent operator

  • usage
  • (Variable 1 == variable 2), only judge whether the values ​​are equal

"===" congruent operator

  • usage
  • (Variable 1 === Variable 2), to judge whether the values ​​are equal and whether the data types are the same

isNaN function

  • usage
  • isNaN (data), the result is true means a number, the result is false means not a number

parsenInt () function

  • usage
  • parseInt (data), you can automatically convert the string to a number, and take integer bits

parseFloat () function

  • usage
  • parseFloat ("string"), can automatically convert strings to numbers

Math.ceil () function

  • usage
  • Math.ceil (number), can be rounded up

Boolean () function

  • usage
  • Boolean (data), you can convert non-Boolean type to Boolean type, you can also omit not write
if(3) 相当于 if(Boolean(3))

String commonly used functions

  • length
    gets the length of the string
  • indexOf
    gets the index of the first occurrence of the specified string in the current string
  • lastIndexOf
    Get the index of the last occurrence of the specified string in the current string
  • replace
    replace
  • substr
    intercept substring
  • substring
    interception substring
  • toLowerCase
    convert lower case
  • toUpperCase
    convert uppercase
  • split
    string

* Note the difference between substr and substring
var str = "avghsdkl"
substr (2,4)-intercept ghsd, including str [4]
substring (2,4)-intercept ghs, excluding str [4]
*

V. Definition of classes and objects

1. Class definition

There are two ways to define

第一种方式:
	function 类名(形式参数列表){
		
		}
第二种方式:
	类名 = function (形式参数列表){
				
		}

2. Object class

  • It is a superclass of all types, any custom type, inherits Object by default.
  • Including the prototype attribute (commonly used), you can dynamically extend the class attribute and function
    constructor attribute
  • Including toString () function
    valueOf () function
    toLocaleString () function
  • The class defined in js inherits Object by default, and integrates all the attributes and functions in the Object class

3. Creation of objects

new 构造方法名(实参);//构造方法名和类名一致
//定义一个学生信息函数
function Student(number,name,score){
	this.number = number;
	this.name = name;
	this.score = score;
}

//函数调用
Student(222,"Jack" ,54);

//创建对象(传几个参数都可以)
var stu1 = new Student();
var stu2 = new Student2(544);
var stu3 = new Student(32,"Helen");

var stu = new Student(111,"Rose",65);
//访问对象属性
alter(stu.number);
alter(stu.name);
alter(stu.score);

//访问对象的另一种方法
alert(stu["number"]);
alert(stu["name"]);
alert(stu["score"]);


4. String objects

Two ways to create

  • The first kind: directly create
    var s = "abc";
  • The second kind: use the internal support class
    var s2 = new String ("abc"); It
    should be noted that String is a built-in class that can be used directly, and the parent class of String is Object
//小String(属于原始类型String)
var x = "king";
alter(typeof x);//"string"

//大String(属于Object类型)
var y = new String("abc");
alter(typeof y);//"object"

6. Events and event registration in JavaScript

1. Event

  • blur
    loses focus

  • focus
    gets focus

  • click
    -click

  • dblclick
    mouse double click

  • keydown
    keyboard press

  • keyup
    keyboard pops up

  • mousedown
    the mouse down

  • mouseover
    mouseover

  • mousemove
    mouse movement

  • mouseout
    mouse leaves

  • mouseup
    mouse up

  • reset
    form reset

  • submit
    form

  • Change the
    options in the drop-down list

  • select
    text is selected

  • The load
    page is loaded (occurs after all elements in the entire HTML page are loaded)

2. Event registration

Register directly via event handler

  • Any event will correspond to an event handle
  • Event handle-attribute exists

Register with js code

The following are specific examples of the two methods


function hello(){
	alter("事件的注册例子”);
}
//第一种方法
<input type="button" value="第一种方法" onclick="hello()"/>
/*
将hello函数注册到按钮上,等待onclick事件发生之后,该函数被浏览器调用,我们称这个为回调函数
回调函数的特点:自己把这个代码写出来了,但是这个函数不是自己负责调用的,由其他程序员负责调用该函数
*/

//第二种方法
<input type="button" value="第二种方法" id="mybtn"/>
<input type="button1" value="第二种方法1" id="mybtn1"/>
//第一步、先获取这个按钮对象
var btn = document.getElementById("mybtn");
//第二步、给按钮对象的onclick属性赋值
btn.onclick = hello;//注意:千万不要加小括号
   						 //这行代码的含义是:将回调函数hello注册到click事件上

//使用匿名事件注册
var btn1 = document.getElementById("mybtn1");
btn1.onclick = function(){
   aleter("使用匿名函数注册事件");
}

Seven, regular expressions

Published 2 original articles · won 0 · 99 visits

Guess you like

Origin blog.csdn.net/Chen_Sir____/article/details/105483779