Fork me on GitHub

JavaScript基础


JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言。

1. Setup & Hello World

  • 有浏览器就能运行JavaScript脚本。
    可以直接再浏览器中运行(以Chrome为例,按F12进入调试模式,然后在Console中写入代码。)

  • 考虑到便捷性和可读性本人使用的是IDE工具,选择自己喜欢的就好。
    Setup & Hello World~点击查看完整代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Setup & Hello World</title>
    </head>
    <body>
    <!-- JavaScript代码要写在script标签内-->
    <script type="text/javascript">
    //这是注释
    /*
    这也是注释
    */
    document.write("hello world!");
    </script>
    </body>
    </html>

2. Using External Files

  • 在html文件中可以在特定位置引入外部js文件的方式来执行js代码,这样的好处就是可以在不同的html文件中引用相同的js代码。
    Using External Files~点击查看完整代码
    1
    <script src="script.js"></script>

    点击查看更多JavaScript使用的相关内容

3. Writing HTML in Javascript

  • JavaScript中的write() 方法可向文档写入 HTML 表达式或 JavaScript 代码。于是我们就可以利用这个特性直接使用js来写html标记语言。
    Setup & Hello World~点击查看完整代码
    1
    2
    document.write("<h2 style='color: silver'>黎雁鹏</h2>");
    document.write("<hr/>");

4. Variables & Data Types

Variables & Data Types~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
var phrase = "To be or not to be "; // 字符串类型
var age = 22; // 整型
var gpa = 2.1; // 浮点型
var isMale =true; // 布尔型
var flaws = null; // null 空
var descraption = undefined; // 暂未定义

document.write(phrase + "<br/>");
phrase = 'lee'; // 即该即变
document.write(phrase + "<br/>");

运行效果如下:

点击查看更多数据类型相关内容

5. Working With Strings

Working With Strings~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
var phrase = "Dp Lee";

document.write(phrase.length + "<br/>");
document.write(phrase.toUpperCase() + "<br/>");
document.write(phrase.charAt(1) + "<br/>");
document.write(phrase.indexOf('e').toString() + "<br/>"); //显示第一次出现的索引
document.write(phrase.lastIndexOf('e').toString() + "<br/>"); //显示最后一次出现的索引 如果找不到返回-1
document.write(phrase.substring(1, 4) + "<br/>"); //左开右闭 不包括第二个参数的
document.write(phrase.substring(phrase.indexOf('L'), phrase.length) + "<br/>");
document.write(phrase.endsWith("Lee") + "<br/>");
var text = "Lee";
document.write(phrase.includes('L') + "<br/>");
document.write(phrase + text + "<br/>");

运行效果如下:

点击查看更多字符串相关内容

6. Math & Numbers

Math & Numbers~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var num = -2;

document.write(2 + num + "<br/>"); //0
document.write(2 - num + "<br/>"); //4
document.write(2 * num + "<br/>"); //-4
document.write(2 / num + "<br/>"); //-1
document.write(2 % num + "<br/>"); //0
document.write(2 + num - (num * 2) / 2 + "<br/>"); //2

//method
document.write(Math.abs(num) + "<br/>"); //2
document.write(Math.max(num, 12, 4) + "<br/>"); //12
document.write(Math.min(num, 12, 4) + "<br/>"); //-2
document.write(Math.round(2.4) + "<br/>"); //2
document.write(Math.round(2.5) + "<br/>"); //3
document.write(Math.sqrt(36) + "<br/>"); //6 开平方
document.write(Math.pow(2, 3) + "<br/>"); //8 2的3次方
document.write(Math.random() + "<br/>"); //0~1随机数
document.write(Math.round(Math.random() * 10) + "<br/>"); //十以内随机数

点击查看更多Math对象相关内容

点击查看更多Number对象相关内容

7. Getting User Input

Getting User Input~点击查看完整代码
1
2
3
var name = window.prompt("waht is your name?", "dplee");
var age = window.prompt("How old are you?");
document.write("Hey " + name + ", how are you today? " + "Do you like being " + age +" years old?");

8. Arrays

Arrays~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var fruits = new Array("apples", "oranges", "peaches");
var vegetables = ["cucumber", "Tomatoes", "Pepper"];
var mix = [
"lee",
21,
false,
vegetables
];
document.write(fruits + vegetables + mix + "<hr/>");
mix[3] = fruits;
document.write(fruits + vegetables + mix + "<hr/>");
document.write(mix.length);

var str1 = "lee, dp, li, yan, peng";
var lee = str1.split(",");
document.write(lee);

点击查看更多数组相关内容

9. Functions

Functions~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function sayHi() {
var name = "DP Lee";
document.write("<h2>Hello "+ name +"!</h2>");
alert("hey! " + name + " How are you!");
}
sayHi();

function sayHi2(name) {
document.write("<h2>Hello "+ name +"!</h2>");
// alert("hey! " + name + " How are you!");
}
sayHi2("DP Lee");
sayHi2("A Fu");

function sayHi3(name, age) {
document.write("<h2>Hello "+ name +"! Do you like being " + age + " years old? </h2>");
// alert("hey! " + name + " How are you!");
}

sayHi3("Lee", 21);


function addition(num1, num2) {
return num1 + num2;
}

document.write(addition(2, 3));

运行结果如下:

点击查看更多函数相关内容

10. Accessing HTML Elements

index.html~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Accessing HTML Elements</title>

</head>
<body>

<!--<script src="script.js"></script>
如果这句代码放在这里那么就不生效
因为下面的 元素在执行到这里时还没有被创建
-->

<h1 id="header">JavaScript</h1>
<a id="link" href="https://www.lee1224.com">一只老菜鸡</a>

<script src="script.js"></script>
</body>
</html>
script.js~点击查看完整代码
1
2
3
4
5
6
7
8
9
var header = document.getElementById("header");
header.innerHTML = "Overridden";
header.style.color = "red";
header.style.backgroundColor = "blue";

var link = document.getElementById("link");
link.innerHTML = "嗨呀~原来是只老菜鸡!";
link.href = "https://www.lee1224.com/JavaScriptjc/";
link.style = "color:red;";

运行结果如下:

11. Event Listeners

index.html~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Event Listeners</title>
<style>
a {
color: #000000;
text-decoration: none;
}

.menu {
color: #ffffff;
border-radius: 5px; /*让边框变得圆润*/
/*color: brown;*/
}
</style>
</head>
<body>

<img id="image" onclick="handleClick()" src="nt.png" width="200">
<br>
<!--<button id="button" onclick="alert('You Clicked Me!')">Click Me</button>-->
<button id="button" onclick="handleClick()">Click Me</button>
<button id="button2" onclick="handleClick2(this)">Click Me 2</button>

<table style="width:100%; height:100%;">
<tr>
<td class="menu"><a href="#">首页</a></td>
</tr>
<tr>
<td class="menu"><a href="#">深海鱼</a></td>
</tr>
<tr>
<td class="menu"><a href="#">香蕉</a></td>
</tr>
</table>

<script src="script.js"></script>

</body>
</html>
script.js~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function handleClick() {
alert("Clicked");
}

function handleClick2(element) {
element.innerHTML = "Clicked";
element.style = "background-color: antiquewhite";
}

var image = document.getElementById("image");

// 添加一个事件监听器,第一个参数写事件名称不需要"on",第二个参数填写方法。
image.addEventListener("mouseover", function () {
this.style = "box-shadow: 2px 2px 2px 2px grey";
this.width = "150";
});

var image = document.getElementById("image");
image.addEventListener("mouseout", function () {
this.style = "";
this.width = "200";
});


// 通过类名来找到一系列元素并且逐个添加事件。
var bs = document.getElementsByClassName("menu");
for (i in bs) {
bs[i].onmouseover = function () {
this.style.backgroundColor = "brown";
};
bs[i].onmouseout = function () {
this.style.backgroundColor = "white";
// this.bgColor = "white";
};
}

运行结果:


点击查看更多addEventListener() 方法相关内容

点击查看更多DOM Event 对象相关内容

12. Building a Messaging App

index.html~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Building a Messaging App</title>
</head>
<body>

<input id="textbox" type="text">
<button id="button">Send</button>
<ul id="messages"></ul>

<script src="script.js"></script>

</body>
</html>
script.js~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
var button = document.getElementById("button");
var messages = document.getElementById("messages");
var texbox = document.getElementById("textbox");

button.addEventListener("click", function () {
var newMessage = document.createElement("li"); // 添加一个新的列标签<li></li>
newMessage.innerHTML = texbox.value; // 把textbo中的内容添加到刚刚添加的列中
messages.appendChild(newMessage); // 把列添加无序列表到中 <ul><li>xxx</li></ul>
texbox.value = "";
});

运行结果如下:

13. If Statements

If Statements~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var isMale = false;
var isTall = true;

if (isMale && isTall){
document.write("You are a tall male!");
}else {
document.write("You are either not male or not tall or neither.");
}

document.write("<hr/>");

if (isMale || isTall){
document.write("You are a male or you are tall or both.");
}else {
document.write("You are not tall and not male.");
}

document.write("<hr/>");

if (isMale && isTall){
document.write("You are a male or you are tall or both.");
}else if(isMale && !isTall){
document.write("You are a shrot male.")
}else if(!isMale && isTall){
document.write("You are not male but you are tall.");
}else {
document.write("You are not tall and not male.");
}

运行结果如下:

点击查看更多if判断语句相关内容

14. If Statements with comparisons

If Statements with comparisons~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function max(num1, num2, num3) {
if (num1 >= num2 && num1 >= num3){
return num1;
}else if (num2 >= num1 && num2 >= num3) {
return num2;
}else {
return num3;
}
}

document.write(max(30, 44, 5));

if ("phrase" == "phrase"){
document.write("True");
}

运行结果如下:

点击查看更多if判断语句相关内容

15. Switch Statements

Switch Statements~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function getDayNum(dayNum) {
var day;

switch (dayNum) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednsday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
default:
day = "Day does't exist, "+dayNum+" isn't a valid number."
}
return day;
}
document.write(getDayNum(9)); // 5

运行结果:


点击查看更多switch相关内容

16. Objects

Objects~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var person = {
name: "DpLee",
age: 21,
isMale: true,
occupation: "Student",
printName: function () {
document.write("<h1>"+this.name+"</h1>");
}
};

document.write(person.name);
person.name = "黎雁鹏";
document.write(person.name);
person.printName();

运行结果如下:

点击查看更多对象相关内容

17. Real world objects

Real world objects~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var myMovie = {
title: "The Social Network",
releaseYear: 2010,
duration: 2.0,
actors: [
{
name: "Jessie Eiseberg",
birthday: new Date("1983/11/05"),
hometown: "New York, New York",
},
{
name: "Roonie Mara",
birthday: new Date("1985/04/17"),
hometown: "Bedford NewYork",
}
]
};

document.write(myMovie.actors[1].birthday);

运行结果:

点击查看更多对象相关内容

18. While Loops

While Loops~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
var i = 1;

while (i <= 10){
document.write(i + "<br/>");
i++;
}

var j = 11;
do{
document.write(i + "<br/>");
j++;
}while (j <= 10);

运行结果:

点击查看更多while循环相关内容

19. Building a Password Checker

Building a Password Checker~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var password = "password";
var response;
var entryCount = 0;
var enterLimite = 3;
var error = false;


while (password != response && !error){
if (entryCount < enterLimite){
response = window.prompt("Enter Password!");
entryCount++;
}else{
error = true;
}

}

if (error)
alert("Too many entries!");
else
alert("You got it!");

20. For Loops

For Loops~点击查看完整代码
1
2
3
4
5
6
7
8
var friends = ["Jim", "Stanley", "Kevin"];
for (var i = 0; i < friends.length; i++){
document.write(friends[i] + "<br/>");
}
// or
for (i in friends){
document.write(friends[i] + "<br/>");
}

运行效果:

点击查看更多for循环相关内容

21. Building a Multiple Choice Quiz

Building a Multiple Choice Quiz~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var questions = [
{
promt: "What color are the apples?\n(a) Red/Green\n(b) Purple\n(c) Orange",
answer: "a"
},
{
promt: "What color are the banabas?\n(a) Teal\n(b) Magenta\n(c) Yellow",
answer: "c"
},
{
promt: "What color are the strawberries?\n(a) Black\n(b) Red\n(c) Blue",
answer: "b"
}
];
var score = 0;
for (var i = 0; i < questions.length; i++) {
var response = window.prompt(questions[i].promt);
if (response == questions[i].answer) {
score++;
alert("Correct!")
} else {
alert("WRONG!")
}
}

alert("You got" + score + "/" + questions.length)

运行效果如下:


22. Nested Loops & 2D Arrays

Nested Loops & 2D Arrays~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var numberGrid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
];

for (var i = 0; i < numberGrid.length; i++) {
for (var j = 0; j < numberGrid[i].length; j++) {
document.write(numberGrid[i][j]);
}
document.write("<br/>");
}

// or
for (i in numberGrid) {
for (j in numberGrid[i]) {
document.write(numberGrid[i][j]);
}
document.write("<br/>");
}


运行效果:


点击查看更多for循环相关内容

23. For Each Loops

index.html~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>For Each Loops</title>
<script src="script.js"></script>
</head>
<body>

<p>乘以: <input type="number" id="multiplyWith" value="10"></p>
<button onclick="numbers.forEach(myFunction)">点我</button>

<p>计算后的值: <span id="demo"></span></p>

<script>
var numbers = [65, 44, 12, 4];

function myFunction(item,index,arr) {
debugger; //使用debugger关键字可在浏览器调试运行查看变量值变化情况有助于理解
arr[index] = item * document.getElementById("multiplyWith").value;
document.getElementById("demo").innerHTML = numbers;
}
</script>

</body>
</html>
script.js~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var books = [
{
title: "Harry Potter",
author: "JK Rowling",
Pages: 300
},
{
title: "Green Eggs & Ham",
author: "Dr. Seuss",
Pages: 25
}
];
var friends = ["Oscar", "Angela", "kevin"];

books.forEach(function (book) {
document.write(book.author + "<hr/>")
});

运行效果:

点击查看更多forEach() 方法相关内容

24. Timing

index.html~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Timing</title>
</head>
<body>
<!--setTimeout-->
<button onclick="setTimeout(sayHi2, 3000, 'dplee')">Click Me</button>
<p id="content"> 请等三秒钟!</p>
<script>
setTimeout("changeState()", 3000);

function changeState() {
let content = document.getElementById('content');
content.innerHTML = "<div style='color:red'>我是三秒后显示的内容!</div>";
}
</script>

<!--setInterval-->
<button onclick="setInterval(sayHi, 2000)">Click Me2</button>
<script>
setInterval("changeState()", 3000);

function changeState() {
let content = document.getElementById('content');
content.innerHTML = "<div style='color:red'>我是三秒后显示的内容!</div>";
}
</script>
<!--以下实例中,setInterval() 方法每 300 毫秒执行 setColor() 函数 ,该函数可以切换背景颜色。-->
<button onclick="startChangeColor()">开始变色</button>
<button onclick="stopColor()">停止切换</button>
<script>
var myVar;

function setColor() {
var x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

function startChangeColor() {
myVar = setInterval(function () {
setColor()
}, 300);
}

function stopColor() {
clearInterval(myVar);
}
</script>


<script src="script.js"></script>
</body>
</html>
script.js~点击查看完整代码
1
2
3
4
5
6
7
function sayHi() {
alert("Hi~ ");
}

function sayHi2(name) {
alert("Hi~ "+ name);
}

运行效果:


点击查看更多计时相关内容

25. Web Storage

index.html~点击查看完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Storage</title>
</head>
<body>
<input id="textbox" type="text" />
<button id="btn">Save</button>
<br><br>
<script src="script.js"></script>
</body>
</html>
script.js~点击查看完整代码
1
2
3
4
5
6
7
8
var textbox = document.getElementById("textbox");
var button = document.getElementById("btn");

textbox.value = localStorage.myName;
addEventListener("click", function () {
localStorage.myName = textbox.value;
});
document.write("<h1>" + localStorage.myName + "</h1>");

运行效果:

是不是有点像cookies的赶脚?

点击查看更多Web 存储相关内容

26. JavaScript 调试

  • 没有调试工具是很难去编写 JavaScript 程序的。
    你的代码可能包含语法错误,逻辑错误,如果没有调试工具,这些错误比较难于发现。
    通常,如果 JavaScript 出现错误,是不会有提示信息,这样你就无法找到代码错误的位置。
  • 在程序代码中寻找错误叫做代码调试。
    调试很难,但幸运的是,很多浏览器都内置了调试工具。
    内置的调试工具可以开始或关闭,严重的错误信息会发送给用户。
    有了调试工具,我们就可以设置断点 (代码停止执行的位置), 且可以在代码执行时检测变量。
    浏览器启用调试工具一般是按下 F12 键,并在调试菜单中选择 “Console” 。

    26.1 console.log() 方法

    如果浏览器支持调试,你可以使用 console.log() 方法在调试窗口上打印 JavaScript 值:
    1
    2
    3
    4
    a = 5;
    b = 6;
    c = a + b;
    console.log(c);
  • 设置断点
    在调试窗口中,你可以设置 JavaScript 代码的断点。
    在每个断点上,都会停止执行 JavaScript 代码,以便于我们检查 JavaScript 变量的值。
    在检查完毕后,可以重新执行代码(如播放按钮)。

26.2 debugger 关键字

  • debugger 关键字用于停止执行 JavaScript,并调用调试函数。
    这个关键字与在调试工具中设置断点的效果是一样的。
    如果没有调试可用,debugger 语句将无法工作。

视频教程地址

本文结束啦 感谢您阅读
路漫漫其修远兮 吾将上下而求索