Home > Web Front-end > JS Tutorial > Summarize and organize the basic syntax of JavaScript

Summarize and organize the basic syntax of JavaScript

WBOY
Release: 2022-08-03 18:18:58
forward
2072 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces issues related to basic grammar. JavaScript is the most popular scripting language on the Internet. Let’s take a look at it together. ,I hope everyone has to help.

Summarize and organize the basic syntax of JavaScript

【Related recommendations: javascript video tutorial, web front-end

Introduction

JavaScript is the most popular scripting language on the Internet. This language can be used for HTML and web, and can be widely used on servers, PCs, laptops, tablets, smartphones and other devices.

JavaScript Features

  • JavaScript is a scripting language.
  • JavaScript is a lightweight programming language.
  • JavaScript is programming code that can be inserted into HTML pages.
  • JavaScript, when inserted into an HTML page, can be executed by all modern browsers.
  • JavaScript is easy to learn.

JavaScript has been standardized as a language by ECMA (European Computer Manufacturers Association) through ECMAScript.

Year Name Description
1997 ECMAScript 1 First version
1998 ECMAScript 2 Version changes
1999 ECMAScript 3 Add regular expression
Add try/catch
ECMAScript 4 Not released
2009 ECMAScript 5 Add "strict mode", strict mode
Add JSON support
2011 ECMAScript 5.1 Version changes
2015 ECMAScript 6 Add classes and modules
2016 ECMAScript 7 Add exponential operator (**)
Add Array.prototype.includes

Usage

Scripts in HTML must be placed between the <script> and </script> tags. Scripts can be placed in the and sections of the HTML page.

Usually, we need to execute code when an event occurs, such as when the user clicks a button. If we put the JavaScript code inside a function, we can call that function when an event occurs.

Example 1: script function in head

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>head标签中script</title>
    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = "这是我的函数";
        }
    </script>
</head>
<body>
<h1>我的函数</h1>
<p id="demo">一段话</p>
<button type="button" onclick="myFunction()">这是函数</button>
</body>
</html>
Copy after login

Example 2: script function in body

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>body中的script</title>
</head>
<body>
<h1>我的函数</h1>
<p id="demo">我的函数</p>
<button type="button" onclick="myFunction()">点击一下</button>
<script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "这是我的函数"
    }
</script>
</body>
</html>
Copy after login

JavaScript can also be placed externally for calling, please note that the external extension is .js.

Example 3: External call to JavaScript

External call.js

function myFunction() {
    document.getElementById(&#39;demo&#39;).innerHTML = "这是我的函数"
}
Copy after login

Call external script

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>调用外部script</title>
</head>
<body>
<p id="demo">一段文字</p>
<button type="button" onclick="myFunction()">尝试一下</button>
<script src="外部脚本.js"></script>
</body>
</html>
Copy after login

Output

JavaScript can be passed through different Way to output data:

  • Use window.alert() to pop up a warning box.
  • Use the document.write() method to write the content into the HTML document.
  • Use innerHTML to write to HTML elements.
  • Use console.log() to write to the browser's console.

Example 1: aler() pop-up window output

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>alert输出</title>
</head>
<body>
<h1>alert输出</h1>
<script>
    window.alert(5 + 6)
</script>
</body>
</html>
Copy after login

Example 2: document.write() output

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>document.write输出</title>
</head>
<body>
<h1>document.write输出</h1>
<script>
    document.write(Date());
    document.write("Hello,Web!");
</script>
</body>
</html>
Copy after login

Example 3: Write to HTMl document

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>写到HTMl文档</title>
</head>
<body>
<h1>写到HTMl文档</h1>
<script>
    function myFunction() {
        document.write("函数输出");
    }
</script>
<button onclick="myFunction()">点击这里</button>
</body>
</html>
Copy after login

Example 4: Use console.log() to write to the browser's console

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用console.log()写入到浏览器的控制台</title>
</head>
<body>
<h1>console.log()写入到浏览器的控制台</h1>
<script >
    a = 5;
    b = 6;
    c = a + b;
    console.log(c)
</script>
</body>
</html>
Copy after login

Syntax introduction

JavaScript is a scripting language, it is a lightweight, But a powerful programming language.

Literals

In programming languages, generally fixed values ​​are called literals.

  • Number literal: can be an integer or a decimal, or scientific notation (e). Such as 3.14, 5.88, etc.
  • String literal: "You can use single quotes or double quotes. Such as "Hello", "Web", etc.
  • Expression literal Quantity: Fixed value used for calculation. 3 2.2, 3.14 * 2, etc.
  • Array: Literal: Define an array. Such as [1,2,3 ,4,5,6].
  • Object (Object: Literal: Define an object. Such as {firstName: "John", lastName: "Doe", age:50, eyeColor :"blue"}.
  • Function literal:Define a function. For example, function myFunction(a, b) { return a * b;}.

Note that in JavaScript, statements need to be terminated with ";".

JavaScrip variables

In programming languages, variables are used to store data values .JavaScript uses the keyword var to define variables, and uses the equal sign to assign values ​​to variables. Variables can operate on each other:

var y = false                                     // 布尔值
var length = 16;                                  // 数字
var points = x * 10;                              // 数字计算
var lastName = "Johnson";                         // 字符串
var cars = ["Saab", "Volvo", "BMW"];              // 数组
var person = {firstName:"John", lastName:"Doe"};  // 对象字典
Copy after login

JavaScript function

In order to be able to be referenced repeatedly The same function reduces the convenience of code writing and maintenance. JavaScript provides function functions, guided by the keyword function:

function myFunc(a, b) {
    return a + b; // 返回a+b结果
}
Copy after login

JavaScript Features

Compared with other languages, JavaScript It has the following characteristics:

  • JavaScript is case-sensitive.
  • JavaScript uses the Unicode character set.
  • JavaScript recommends using camel case naming to define variables and avoid naming keywords .
  • JavaScript is a weakly typed language, and variables are defined with the var keyword.
##booleanenumintswitch##breakbytecase##catchfinalnativethrowscharfinallynewtransientclassfloatnulltrueconstforpackagetrycontinuefunctionprivatetypeofdebugger gotoprotectedvardefaultifpublicvoiddeleteimplementsreturnvolatiledoimportshortwhiledoubleinstatic with

JavaScript注释(与Java相同)

// 这是代码:单句注释,在编辑器一般是ctrl + L键。

/* 这是代码 */:多行注释,在编辑器一般是ctrl + shift + L键。

语句

JavaScript语句向浏览器发出的命令,告诉浏览器该做什么。下面的JavaScript语句向id="demo"的 HTML元素输出文本"Hello World!" :

document.getElementById("demo").innerHTML = "Hello World!";
Copy after login

与Python不同的是,JavaScript代码块都是在大括号中的,这点像极了Java。

Java标识符

JavaScript keywords (in alphabetical order)
abstractelseinstanceofsuper
exportinterfacesynchronized
extendsletthis
false longthrow
常见JavaScript标识符
语句描述
break用于跳出循环。
catch语句块,在 try 语句块执行出错时执行 catch 语句块。
continue跳过循环中的一个迭代。
do ... while执行一个语句块,在条件语句为 true 时继续执行该语句块。
for在条件语句为 true 时,可以将代码块执行指定的次数。
for ... in用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)。
function定义一个函数
if ... else用于基于不同的条件来执行不同的动作。
return退出函数
switch用于基于不同的条件来执行不同的动作。
throw抛出(生成)错误 。
try实现错误处理,与 catch 一同使用。
var声明一个变量。
while当条件语句为 true 时,执行语句块。

大部分语言能够自动补全空格,我们建议在运算符两边加上空格,这样清晰美观,但是要注意在HTML中空格的是要留意用法的,切勿混谈。在JavaScript中,下面两句话是一样的:

var a = 10;
var b=10;
Copy after login

与Python相似,JavaScript也是脚本语言,属于解释型。

对象

定义对象

任何事物都是对象,具有相同特点的事物中抽象出来的一个特点实例。如人类中的小明。

在JavaScript中,对象就是是属性变量的容器,类似Python中的字典,Java中的哈希映射,其中定义了对象的属性。

var people = {
    firstName: "Mike",
    lastName: "Smith",
    age: "18",
    address: "Beijing",
    job: "Student"
};
Copy after login

以上就是对象定义,当然你也可以写作一行,我这样是为了美观,以后也强烈大家这样写。

访问对象属性

可以说 "JavaScript 对象是变量的容器"。但是,我们通常认为 "JavaScript 对象是键值对的容器"。键值对通常写法为key : value(键与值以冒号分割),键值对在JavaScript对象通常称为对象属性。我们访问属性也是通过万能的" . "(大部分语言都是用的这个)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>这是网站</title>
</head>
<body>
<h1>访问类属性</h1>
<!--下面语句一定要在script之前-->
<p id="demo"></p>
<script>
    var people = {
        firstName: "Mike",
        lastName: "Smith",
        age: "18",
        address: "Beijing",
        job: "Student"
    };
    document.getElementById("demo").innerHTML =
        people["firstName"] + "." + people.lastName;
</script>
</body>
</html>
Copy after login

两种访问方式,你可以使用 对象名 .property 或 对象名.["property"] 。

函数

函数是由事件驱动的或者当它被调用时执行的可重复使用的代码块。当调用该函数时,会执行函数内的代码。可以在某事件发生时直接调用函数(比如当用户点击按钮时),并且可由 JavaScript 在任何位置进行调用。

参数与返回值

在调用函数时,您可以向其传递值,这些值被称为参数,参数个数不限。

function myFunction(var1,var2)
{
代码
}

参数在调用时,应该严格按照其顺序传参,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>这是一个JavaScript网站</title>
</head>
<body>
<h1>函数参数传递问题</h1>
<p>点击下面按钮调用</p>
<button onclick="myFunc(&#39;Mike&#39;,&#39;18&#39;,&#39;Beijing&#39;)">点击这里</button>
<script>
    function myFunc(name, age, address) {
        alert("My name is " + name + ", age is " + age + " and my home is in " + address);
    }
</script>
</body>
</html>
Copy after login

JavaScript函数允许有返回值,返回关键字为return。当函数返回值后,函数将停止执行,在return后面的语句将不会被执行。

实例:计算两个数的乘积并返回结果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript网站</title>
</head>
<body>
<h1>计算两个数的值返回</h1>
<p id="demo"></p>
<script>
    function myFunc(a, b) {
        return a * b;
    }

    document.getElementById("demo").innerHTML = myFunc(3, 4);
</script>
</body>
</html>
Copy after login

变量

JavaScript变量分为两种:

  • 全局变量:在函数外声明的变量是全局变量,网页上的所有脚本和函数都能访问它。
  • 局部变量:在JavaScript函数内部声明的变量(使用 var)是局部变量,所以只能在函数内部访问它。

当我们向未声明的JavaScript变量分配值时,该变量将被自动作为window的一个属性。如下列语句:

name = "Mike";
Copy after login

将声明window的一个属性name。非严格模式下给未声明变量赋值创建的全局变量,是全局对象的可配置属性,可以删除。如:

var var1 = 1; // 不可配置全局属性
var2 = 2; // 没有使用 var 声明,可配置全局属性

console.log(this.var1); // 1
console.log(window.var1); // 1

delete var1; // false 无法删除
console.log(var1); //1

delete var2; 
console.log(delete var2); // true
console.log(var2); // 已经删除 报错变量未定义
Copy after login

事件

描述

HTML事件是发生在HTML元素上的事情。当在 HTML 页面中使用JavaScript时, JavaScript可以触发这些事件。

HTML事件可以是浏览器行为,也可以是用户行为。以下是HTM 事件的实例:

  • HTML 页面完成加载
  • HTML input 字段改变时
  • HTML 按钮被点击

通常,当事件发生时,你可以做些事情。在事件触发时JavaScript可以执行一些代码。HTML元素中可以添加事件属性,使用JavaScript代码来添加HTML元素。

  • 单引号:<some-HTML-element some-event='JavaScript 代码'>
  • 双引号:<some-HTML-element some-event="JavaScript 代码">
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript事件</title>
</head>
<body>
<h1>JavaScript事件处理两种方式</h1>
<p id="demoOne"></p>
<button onclick="getElementById(&#39;demoOne&#39;).innerHTML=Date()">点击查看时间1</button>
<p id="demoTwo"></p>
<button onclick="this.innerHTML=Date()">点击查看时间2</button>
</body>
</html>
Copy after login

JavaScript通常是多行代码,比较差常见的就是通过事件属性调用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript事件</title>
</head>
<body>
<h1>JavaScript事件之属性调用</h1>
<p>点击执行<em>myFunc()</em>函数</p>
<button onclick="myFunc()">点击这里</button>
<p id="one"></p>
<script>
    function myFunc() {
        document.getElementById("one").innerHTML = Date();
    }
</script>
</body>
</html>
Copy after login
常见HTML事件
事件描述
onchangeHTML 元素改变
onclick用户点击 HTML 元素
onmouseover用户在一个HTML元素上移动鼠标
onmouseout用户从一个HTML元素上移开鼠标
onkeydown用户按下键盘按键
onload浏览器已完成页面的加载

后续会继续学习更多事件。

事件作用

事件可以用于处理表单验证,用户输入,用户行为及浏览器动作:

  • 页面加载时触发事件
  • 页面关闭时触发事件
  • 用户点击按钮执行动作
  • 验证用户输入内容的合法性

可以使用多种方法来执行 JavaScript 事件代码:

  • HTML 事件属性可以直接执行 JavaScript 代码
  • HTML 事件属性可以调用 JavaScript 函数
  • 你可以为 HTML 元素指定自己的事件处理程序
  • 你可以阻止事件的发生

字符串

字符串:一系列字符的集合。

var a = "abc";
var b = "Hello";
Copy after login

与Python类似,可以使用索引来访问字符串中的每个字符:

var c = b[1];           // e
Copy after login

length

该属性可以计算字符串的长度。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>字符串长度</title>
</head>
<body>
<script>
    var txtOne = "Hello World!";
    document.write("<p>" + txtOne.length + "</p>");
    var txtTwo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    document.write("<p>" + txtTwo.length + "</p>");
</script>
</body>
</html>
Copy after login

JavaScript也有一些特殊字符,例如当我们要打印引号时,需要加上“\”来进行转义,否则编译器无法解析。

JavaScript常见特殊字符
代码输出
\'单引号
\"双引号
\\反斜杠
\n换行
\r回车
\ttab(制表符)
\b退格符
\f换页符

字符串作为对象

通常,JavaScript字符串是原始值,可以使用字符创建: var firstName = "Mike",但我们也可以使用new关键字将字符串定义为一个对象:var firstName = new String("Mike"),这点与Java类似。

字符串常见属性
属性描述
constructor返回创建字符串属性的函数
length返回字符串的长度
prototype允许您向对象添加属性和方法
字符串常见方法
方法描述
charAt()返回指定索引位置的字符
charCodeAt()返回指定索引位置字符的 Unicode 值
concat()连接两个或多个字符串,返回连接后的字符串
fromCharCode()将 Unicode 转换为字符串
indexOf()返回字符串中检索指定字符第一次出现的位置
lastIndexOf()返回字符串中检索指定字符最后一次出现的位置
localeCompare()用本地特定的顺序来比较两个字符串
match()找到一个或多个正则表达式的匹配
replace()替换与正则表达式匹配的子串
search()检索与正则表达式相匹配的值
slice()提取字符串的片断,并在新的字符串中返回被提取的部分
split()把字符串分割为子字符串数组
substr()从起始索引号提取字符串中指定数目的字符
substring()提取字符串中两个指定的索引号之间的字符
toLocaleLowerCase()根据主机的语言环境把字符串转换为小写,只有几种语言(如土耳其语)具有地方特有的大小写映射
toLocaleUpperCase()根据主机的语言环境把字符串转换为大写,只有几种语言(如土耳其语)具有地方特有的大小写映射
toLowerCase()把字符串转换为小写
toString()返回字符串对象值
toUpperCase()把字符串转换为大写
trim()移除字符串首尾空白
valueOf()返回某个字符串对象的原始值

==与===区别

1、对于 string、number 等基础类型,== 和 === 是有区别的

  • a)不同类型间比较,==之比较"转化成同一类型后的值"看"值"是否相等,===如果类型不同,其结果就是不等。
  • b)同类型比较,直接进行 "值" 比较,两者结果一样。

2、对于 Array,Object 等高级类型,== 和 === 是没有区别的

进行 "指针地址" 比较

3、基础类型与高级类型,== 和 === 是有区别的

  • a)对于 ==,将高级转化为基础类型,进行 "值" 比较
  • b)因为类型不同,=== 结果为 false

4、!= 为 == 的非运算,!== 为 === 的非运算

var num=1;

var str="1";

var test=1;

test == num   //true 相同类型 相同值 

test === num  //true 相同类型 相同值 

test !== num  //false test与num类型相同,其值也相同, 非运算肯定是false 

num == str   //true  把str转换为数字,检查其是否相等。 

num != str   //false  == 的 非运算 

num === str  //false  类型不同,直接返回false 

num !== str  //true   num 与 str类型不同 意味着其两者不等 非运算自然是true啦
Copy after login

运算符

JavaScript常见运算符(y=5)
运算符描述例子x 运算结果y 运算结果
+加法x=y+275
-减法x=y-235
*乘法x=y*2105
/除法x=y/22.55
%取模(余数)x=y%215
++自增x=++y66
x=y++56
--自减x=--y44
x=y--54
JavaScript常见赋值运算符(x=10,y=5)
运算符例子等同于运算结果
=x=y x=5
+=x+=yx=x+yx=15
-=x-=yx=x-yx=5
*=x*=yx=x*yx=50
/=x/=yx=x/yx=2
%=x%=yx=x%yx=0
##==== is equal to x==8x==5##===falsex ===5true!=true!==true##x!==5> is greater than x>8 is less than true is greater than or equal tofalse is less than or equal to true is less than or equal to x<=8
JavaScript common comparison operators (x=5)
OperatorDescriptionComparison The return value
false
true
Absolutely equal (both value and type are equal)x==="5"
is not equal to x!=8
Not absolutely equal (one of the value and type is not equal, or both are not equal Equal)x!=="5"
false
false##<
x<8 >=
x>=8 <=
x<=8## <=
true## Commonly used logical operators in JavaScript (x=6, y=3)
OperatorExample##&&and(x < 10 && y > 1) is true||or(x==5 || y==5) is false! not!(x==y) is true

JavaScript 还包含了基于某些条件对变量进行赋值的条件运算符。如:

variablename=(condition)?value1:value2
Copy after login

条件判断

在 JavaScript 中,我们可使用以下条件语句:

  • if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
  • if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
  • if...else if....else 语句- 使用该语句来选择多个代码块之一来执行
  • switch 语句 - 使用该语句来选择多个代码块之一来执行

if语句

条件为true时才会执行代码。如:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>JavaScript网站</title>
</head>
<body>
<h1>这是if语句</h1>
<button onclick="myFunc()">点击这里</button>
<p id="one"></p>
<script>
    function myFunc() {
        var x = "";
        var time = new Date().getHours();
        if (time < 20) {
            x = "Hello, Before 20:00";
        }
        document.getElementById("one").innerHTML = x;
    }
</script>
</body>
</html>
Copy after login

if...else语句

使用 if....else语句在条件为true时执行代码,在条件为false时执行其他代码。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>JavaScript网站</title>
</head>
<body>
<h1>这是if...else语句</h1>
<button onclick="myFunc()">点击这里</button>
<p id="one"></p>
<script>
    function myFunc() {
        var x = "";
        var time = new Date().getHours();
        if (time < 20) {
            x = "Hello, Before 20:00";
        }else {
            x = "Hello, After 20:00";
        }
        document.getElementById("one").innerHTML = x;
    }
</script>
</body>
</html>
Copy after login

多重if..else语句

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>JavaScript网站</title>
</head>
<body>
<h1>多重if...else语句</h1>
<button onclick="myFunc()">点击这里</button>
<p id="one"></p>
<script>
    function myFunc() {
        var x = "";
        var time = new Date().getHours();
        if (time < 12) {
            x = "上午好";
        } else if (time < 14) {
            x = "中午好";
        }
        else {
            x = "下午好";
        }
        document.getElementById("one").innerHTML = x;
    }
</script>
</body>
</html>
Copy after login

switch语句

使用switch语句来选择要执行的多个代码块之一。如:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>JavaScript网站</title>
</head>
<body>
<h1>switch语句</h1>
<button onclick="myFunc()">点击这里</button>
<p id="one"></p>
<script>
    function myFunc() {
        var x = "";
        var time = new Date().getMonth();
        switch (time) {
            case 0:
                x = "January";
                break;
            case 1:
                x = "February";
                break;
            case 2:
                x = "March";
                break;
            case 3:
                x = "April";
                break;
            case 4:
                x = "May";
                break;
            case 5:
                x = "Jane";
                break;
            case 6:
                x = "July";
                break;
            case 7:
                x = "August";
                break;
            case 8:
                x = "September";
                break;
            case 9:
                x = "October";
                break;
            case 10:
                x = "November";
                break;
            case 11:
                x = "December";
                break;
            default:
                x = "ERROR";
        }
        document.getElementById("one").innerHTML = x;
    }
</script>
</body>
</html>
Copy after login

循环

JavaScript 支持不同类型的循环:

  • for - 循环代码块一定的次数
  • for/in - 循环遍历对象的属性
  • while - 当指定的条件为 true 时循环指定的代码块
  • do/while - 同样当指定的条件为 true 时循环指定的代码块

for循环

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JavaScript循环</title>
</head>
<body>
<h1>点击按钮循环代码5次。</h1>
<button onclick="myFunc()">点击这里</button>
<p id="demo"></p>
<script>
    function myFunc() {
        var x = "";
        for (var i = 0; i < 5; i++) {
            x = x + "该数字为 " + i + "<br>";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>
</body>
</html>
Copy after login

fo /in循环

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>
<p>点击下面的按钮,遍历对象person属性</p>
<button onclick="myFunc()">点击这里</button>
<p id="one"></p>
<script>
    function myFunc() {
        let x;
        let text = "";
        const person = {
            firstName: "Bill",
            lastName: "Gates",
            age: 56
        };
        for (x in person) {
            text = text + " " + person[x];
        }
        document.getElementById("one").innerHTML = text;
    }
</script>
</body>
</html>
Copy after login

while循环

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>
<p>点击按钮,i小于5就会打印输出</p>
<button onclick="myFunc()">点击这里</button>
<p id="one">显示在这里</p>
<script>
    function myFunc() {
        let x = "", i = 0;
        while (i < 5) {
            x = x + "这个数字为" + i + "<br>";
            i++;
        }
        document.getElementById("one").innerHTML = x
    }
</script>
</body>
</html>
Copy after login

do/while循环

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>
<p>点击按钮,打印小于5的数</p>
<button onclick="myFunc()">点击这里</button>
<p id="one"></p>
<script>
    function myFunc() {
        let x = "";
        let i = 0;
        do {
            x = x + "该数字为" + i + "<br>";
            i++;
        }
        while (i < 5);
        document.getElementById("one").innerHTML=x;
    }
</script>
</body>
</html>
Copy after login

for循环和while循环比较

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>这是funcOne</p>
<button onclick="funcOne()">点击funcOne</button>
<p id="one">funcOne在这里</p>

<p>这是funcTwo</p>
<button onclick="funcTwo()">点击funcTwo</button>
<p id="two">funcTwo在这里</p>

<script>
    function funcOne() {
        numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        let i = 0;
        let addRes = 0;
        while (numbers[i]) {
            addRes += numbers[i];
            i++;
        }
        document.getElementById("one").innerHTML = addRes + "<br>";

    }

    function funcTwo() {
        numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        let i = 0;
        let mulRes = 1;
        for (; numbers[i];) {
            mulRes *= numbers[i];
            i++;
        }
        document.getElementById("two").innerHTML = mulRes + "<br>";
    }
</script>

</body>
</html>
Copy after login

Break和Continue

break 语句用于跳出循环。continue 用于跳过循环中的一个迭代。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>
<p>这是continue和break语句</p>
<button onclick="funcOne()">点击funcOne</button>
<p id="one">这是funcOne</p>
<br>
<br>
<br>
<br>
<br>
<br>
<button onclick="funcTwo()">点击funcTwo</button>
<p id="two">这是funcTwo</p>
<script>
    function funcOne() {
        let x = "";
        let i = 0;
        for (i = 0; i < 10; i++) {
            if (i < 5) {
                break;
            }
            x = x + "该数字为" + i + "<br>";
        }
        document.getElementById("one").innerHTML = x;
    }

    function funcTwo() {
        let x = "";
        let i = 0;
        for (i = 0; i < 10; i++) {
            if (i === 8) {
                continue;
            }
            x = x + "该数字为" + i + "<br>";
        }
        document.getElementById("two").innerHTML = x;
    }
</script>

</body>
</html>
Copy after login

typeof、null和undefined

使用typeof操作符来检测变量的数据类型。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>
<p id="one"></p>
<script>
    document.getElementById("one").innerHTML =
        typeof "john" + "<br>" +
        typeof 3.14 + "<br>" +
        typeof false + "<br>" +
        typeof [1, 2, 3, 4] + "<br>" +
        typeof {name: &#39;john&#39;, age: 34};

</script>

</body>
</html>
Copy after login

在JavaScript中,数组是一种特殊的对象类型。 因此 typeof [1,2,3,4] 返回 object。

null表示空,也就是”什么也没有“。当使用typeof 检测时,返回object。对象可以使用undefined来清空。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>
<p>one:</p>
<p id="one"></p>
<p>two:</p>
<p id="two"></p>

<script>
    var person = {firstName: "Bill", lastName: "Gates", age: 50};
    var person = null;
    document.getElementById("one").innerHTML = typeof person;
    person = undefined
    document.getElementById("two").innerHTML = typeof person;
</script>

</body>
</html>
Copy after login

constructor属性

constructor属性返回所有JavaScript变量的构造函数。可以使用constructor属性来查看对象是否为数组或者是否为日期 (包含字符串 "Date")等。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>constructor属性返回变量或者构造函数</p>
<p id="one">HRER</p>
<script>
    document.getElementById("one").innerHTML =
        "Hello".constructor + "<br>" +
        3.14.constructor + "<br>" +
        false.constructor + "<br>" +
        [1, 2, 3].constructor + "<br>" +
        {name: "Hello", age: 18}.constructor + "<br>" +
        new Date().constructor + "<br>" +
        function () {
        }.constructor;
</script>

</body>
</html>
Copy after login

类型转换

JavaScript 变量可以转换为新变量或其他数据类型:

  • 通过使用JavaScript函数
  • 通过JavaScript自身自动转换
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>String()方法可以将数字转化为字符串</p>
<p id="one">HERE</p>
<p>toString()方法可以将数字转化为字符串</p>
<p id="two">HERE</p>
<script>
    let x = 123;
    document.getElementById("one").innerHTML =
        String(x) + "<br>" +
        String(123) + "<br>" +
        String(100 + 23);
    document.getElementById("two").innerHTML =
        x.toString() + "<br>" +
        (123).toString() + "<br>" +
        (100 + 123.2).toString();
</script>

</body>
</html>
Copy after login

一元运算符+

Operator+可用于将变量转换为数字:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<P>typeof操作符返回变量或者表达式类型</P>
<button onclick="myFuncOne()">CLICK HERE ONE</button>
<p id="one">HERE</p>
<button onclick="myFuncTwo()">CLICK HERE TWO</button>
<p id="two">HERE</p>
<script>
    function myFuncOne() {
        let y = "5";
        let x = +y;
        document.getElementById("one").innerHTML =
            typeof y + "<br>" + x + "<br>" + typeof x;
    }

    function myFuncTwo() {
        let a = "Hello";
        let b = +a;
        document.getElementById("two").innerHTML =
            typeof a + "<br>" + b + "<br>" + typeof b;
    }

</script>
</body>
</html>
Copy after login
Description
JavaScript类型转换
原始值转换为数字转换为字符串转换为布尔值
false0"false"false
true1"true"true
00"0"false
11"1"true
"0"0"0"true
"000"0"000"true
"1"1"1"true
NaNNaN"NaN"false
InfinityInfinity"Infinity"true
-Infinity-Infinity"-Infinity"true
""0""false
"20"20"20"true
"Runoob"NaN"Runoob"true
[ ]0""true
[20]20"20"true
[10,20]NaN"10,20"true
["Runoob"]NaN"Runoob"true
["Runoob","Google"]NaN"Runoob,Google"true
function(){}NaN"function(){}"true
{ }NaN"[object Object]"true
null0"null"false
undefinedNaN"undefined"false

正则表达式

正则表达式(英语:Regular Expression,在代码中常简写为regex、regexp或RE)使用单个字符串来描述、匹配一系列符合某个句法规则的字符串搜索模式。

search()

用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串,并返回子串的起始位置。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>收索字符串,匹配位置</p>

<button onclick="myFuncOne()">CLICK HERE ONE</button>
<p id="one">HERE</p>

<button onclick="myFuncTwo()">CLICK HERE TWO</button>
<p id="two">HERE</p>

<script>
    function myFuncOne() {
        let str = "Hello,World!";
        document.getElementById("one").innerHTML = str.search(/World/i);
    }

    function myFuncTwo() {
        let str = "Welcome to China!";
        document.getElementById("two").innerHTML = str.search("China");
    }
</script>

</body>
</html>
Copy after login

replace()

用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>正则表达式replace()替换</p>

<button onclick="myFuncOne()">CLICK ONE</button>
<p id="one">Hello,Java</p>

<button onclick="myFuncTwo()">CLICK TWO</button>
<p id="two">Hello,Java</p>

<script>
    function myFuncOne() {
        let str = document.getElementById("one").innerHTML;
        document.getElementById("one").innerHTML = str.replace(/Java/i, "Python");
    }

    function myFuncTwo() {
        let str = document.getElementById("two").innerHTML;
        document.getElementById("two").innerHTML = str.replace("Java","JavaScipt");
    }
</script>

</body>
</html>
Copy after login

正则表达式模式

正则表达式修饰符
修饰符描述
i执行对大小写不敏感的匹配。
g执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。
m执行多行匹配。
正则表达式特殊字符
表达式描述
[abc]查找方括号之间的任何字符。
[0-9]查找任何从 0 至 9 的数字。
(x|y)查找任何以 | 分隔的选项。
正则表达式量词
量词描述
n+匹配任何包含至少一个 n 的字符串。
n*匹配任何包含零个或多个 n 的字符串。
n?匹配任何包含零个或一个 n 的字符串。

test()

用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回true,否则返回false。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<script>
    let obj = new RegExp("e");
    let boolOne = obj.test("Hello,This is JavaScript");
    let boolTwo = obj.test("This is JavaScript");
    document.write(boolOne + "<br>" + boolTwo);
</script>

</body>
</html>
Copy after login

exec()

用于检索字符串中的正则表达式的匹配,该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<script>
    let obj = new RegExp(/e/);
    resOne = obj.exec("Hello,This is JavaScript");
    resTwo = obj.exec("This is JavaScript");
    /*没有就是null*/
    document.write(resOne + "<br>" + resTwo);
</script>

</body>
</html>
Copy after login

错误异常

错误类型

  • 当 JavaScript 引擎执行 JavaScript 代码时,会发生各种错误。
  • 可能是语法错误,通常是程序员造成的编码错误或错别字。
  • 可能是拼写错误或语言中缺少的功能(可能由于浏览器差异)。
  • 可能是由于来自服务器或用户的错误输出而导致的错误。
  • 当然,也可能是由于许多其他不可预知的因素。

try...catch

try语句允许我们定义在执行时进行错误测试的代码块,catch语句允许我们定义当try代码块发生错误时,所执行的代码块。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<input type="button" value="查看消息" onclick="myFunc()">
<script>
    let txt = "";

    function myFunc() {
        try {
            alert111("Hello,World!")
        }
        catch (err) {
            txt = "这里有一个错误\n\n";
            txt += "错误描述:" + err.message + "\n\n";
            txt += "点击确定继续\n\n";
            alert(txt)
        }
    }
</script>

</body>
</html>
Copy after login

throw

throw语句允许我们创建自定义错误。正确的技术术语是:创建或抛出异常(exception)。如果把throw与try和catch一起使用,那么您能够控制程序流,并生成自定义的错误消息。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>请输入一个5-10之间的数字</p>
<label for="one"></label><input id="one" type="text">
<button type="button" onclick="myFunc()">CLICK</button>
<p id="message">HERE</p>

<script>
    function myFunc() {
        let message;
        let x;
        message = document.getElementById("message");
        message.innerHTML = "";
        x = document.getElementById("one").value;
        try {
            if (x === "")
                throw "值为空";
            if (isNaN(x))
                throw "不是数字";
            x = Number(x);
            if (x < 5)
                throw "太小";
            if (x > 10)
                throw "太大";
        } catch (error) {
            message.innerHTML = "错误" + error;
        }
    }
</script>

</body>
</html>
Copy after login

函数调用

JavaScript 函数有 4 种调用方式,每种方式的不同在于this的初始化。一般而言,在Javascript中,this指向函数执行时的当前对象。

调用1:作为一个函数调用

one

function myFunc(a, b) {
    return a * b;
}

myFunc(1, 2);
Copy after login

two

function myFunc(a, b) {
    return a * b;
}

window.myFunc(1, 2);
Copy after login

调用2:函数作为方法调用

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>函数作为方法调用</p>
<p id="one">HERE</p>

<script>
    let myObject = {
        firstName: "Bill",
        lastName: "Gates",
        fullName: function () {
            return this.firstName + " " + this.lastName;
        }
    };
    document.getElementById("one").innerHTML = myObject.fullName();
</script>

</body>
</html>
Copy after login

调用3:使用构造函数调用函数

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>该实例中,myFunc()是函数的构造函数</p>
<p id="one"></p>
<script>
    function myFunc(argOne, argTwo) {
        this.Name = argOne;
        this.Number = argTwo;
    }

    let x = new myFunc("Hello", 123);
    document.getElementById("one").innerHTML = x.Name;
</script>

</body>
</html>
Copy after login

调用4:作为函数方法调动函数

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>作为函数方法调动函数</p>
<p id="one">HERE</p>

<script>
    let obj, array;

    function myFunc(a, b) {
        return a * b;
    }

    array = [5, 6];
    obj = myFunc.apply(obj, array);
    document.getElementById("one").innerHTML = obj;
</script>

</body>
</html>
Copy after login

闭包

内嵌函数

实际上,在JavaScript中,所有函数都能访问它们上一层的作用域。JavaScript支持嵌套函数,嵌套函数可以访问上一层的函数变量。内嵌函数plus()可以访问父函数的counter变量:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>内嵌函数</p>
<p id="one">HERE</p>

<script>
    document.getElementById("one").innerHTML = add();

    function add() {
        let counter = 0;

        function plus() {
            counter += 1;
        }

        plus();
        return counter;
    }
</script>

</body>
</html>
Copy after login

闭包

函数的自我调用称为bibao

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<p>局部计数器</p>
<button type="button" onclick="myFunc()">计数器</button>
<p id="one">HERE</p>

<script>
    let add = (function () {
        let counter = 0;
        return function () {
            return counter += 1;
        }
    })();

    function myFunc() {
        document.getElementById("one").innerHTML = add();
    }
</script>
</body>
</html>
Copy after login

【相关推荐:javascript视频教程web前端

The above is the detailed content of Summarize and organize the basic syntax of JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template