1 开始
1.1 什么是JavaScript
JavaScript可被用于:
- 前端开发人员
- 后端开发人员
- 全栈开发人员
JavaScript能做什么?
- Web/Mobile应用
- 实时网络应用
- 命令行工具
- 游戏
JavaScript运行于什么地方?
- 浏览器,JavaScript引擎(FireFox: SpiderMonkey, Chrome: V8)
- Node, 浏览器外运行JavaScript的运行时环境
JavaScript vs ECMAScript?
- ECMAScript只是一个规范,第一版发行于1997年,最新的版本目前是ES2015/ES6
- Javascript是一种被ECMAScript确认符合该规范的编程语言
1.2 配置开发环境
编辑器:
- Visual Studio Code
- Sublime Text
- Atom
Node.js为JavaScript提供了一个浏览器之外的运行环境,请下载并安装方便学习。
VS Code安装完成后,命令行执行下面指令:
$ cd ~ $ mkdir apps $ cd apps $ mkdir demo01 $ cd demo01 $ code .
进入VSCode后,添加"index.html"文件,并拷贝以下代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Hello, World!</h1> </body> </html>
安装VS Code的扩展插件Live Server,完成后以Live Server打开index.html正常则安装成功。
1.3 浏览器中的JavaScript
可以把JavaScript嵌入到HTML文件head或body中的任何部分,如下是把JavaScript嵌入到HTML中的body部分:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Hello, World!</h1> <script> // JavaScript代码 console.log('Hello, World'); </script> </body> </html>
Live Server中打开index.html然后按F12并点击Console标签查看控制台输出:Hello, World
1.4 分离HTML和JavaScript
VS Code环境中,index,html同目录下,添加index.js,并添加以下代码到该index.js文件:
console.log("Hello, My World!");
VS Code环境,回到index.html并更新index.html为以下内容:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Hello, World!</h1> <script src="index.js"></script> </body> </html>
以Live Server打开index.html文件,F12后并点击Console标签查看控制台输出。
1.5 Node中的JavaScript运行环境
如果node.js正确安装完成,则可以从VS Code的终端直接运行index.js,方法如下:
- 从VS Code菜单选择终端,在终端运行下面命令运行index.js
$ node index.js
Hello, My World!
2 JavaScript基础
2.1 变量
JavaScript使用变量在内存中临时存储数据:
- var 关键字用于声明一个变量
- let 关键字与var相似也声明一个变量
更新index.js为以下代码:
let name;
console.log(name);
命令行(终端)运行index.js:
$ node basics.js
undefined
终端输出undefined表示name变量没有定义。更新index.js为:
let name = 'Jinzd';
console.log(name);
终端运行node index.js控制台输出Jinzd
小结:
- 变量名不能是JavaScript保留字
- 变量名应该有意义
- 变量名不能以数字开始
- 变量名不能包含空格或减号“-”
- 变量名是大小写敏感的
- 变量命名规则通常有Camel规则(firstName)或Pascal规则(FirstName)
2.2 常量
普通变量的值设定之后是可以被更改的:
let interestRate = 0.3; interestRate = 1; console.log(interestRate);
而常量的值在设置之后不能再被修改:
const interestRate = 0.3; interestRate = 1; console.log(interestRate);
运行上面代码会产生错误信息:Assignment to constant variable.
2.3 JavaScript原生数据类型和引用类型
JavaScript原生数据类型包括:
- String
- Number
- Boolean
- undefined
- null
JavaScript还大量使用引用类型:
- Reference Types
更新index.js为以下内容,并以node运行它:
let name = 'jinzd'; // string literal let age = 30; // number literal let isApproved = true; // boolean literal let isChecked = false; // boolean literal let firstName; // undefined let lastName = undefined; // undefined let middleName = null; // typeof middleName => object console.log(typeof middleName); // object
2.4 动态类型
JavaScript是一种动态语言,与之相对的是静态语言,如:Java,静态语言变量声明后其类型不能再改变;而动态语言的变量类型则可以被改变。
静态语言:
string name = "Jinzd";
动态语言:
let v = 'demo'; // string literal console.log(typeof v); v = 30; console.log(typeof v);
2.5 Objects
对象属于引用类型,引用类型包括:
- Object
- Array
- Function
按下更新index.js并在控制台以node运行它:
let person = { name: 'Mosh', age: 30 }; console.log(person); person.name = 'John'; console.log(person); person['name'] = 'Mary'; console.log(person); let section = 'name'; person[section] = 'Jim' console.log(person);
2.6 Arrays 数组
参看以下数组例子,并更新到index.js然后以node运行它:
let selectColors = ['red', 'blue']; console.log(selectColors); console.log(selectColors[0]); selectColors[2] = 'yellow'; console.log(selectColors); selectColors[3] = 5; console.log(selectColors); selectColors[2] = true; console.log(selectColors); console.log(typeof selectColors); // object console.log(selectColors.length); // 4
2.7 Functions函数
function greet(name, lastName) { console.log('Hello, ' + name + ' ' + lastName); } greet('John', 'Smith'); greet('mary');
更新上代码到index.js然后以node运行它,输出:
Hello, John Smith Hello, mary undefined
2.8 函数类型
函数包括两类:
- 函数执行一个任务没有返回值
- 函数执行一组计算任务然后返回一个值
执行任务无返回值函数参看2.7节,下函数执行任务并返回值:
function square(number) { return number * number; } console.log(square(4));
3 操作符
3.1 JavaScript操作符
JavaScript包括以下操作符:
- 算术操作符(Arithmetic)
- 赋值操作符(Assignment)
- 比较操作符(Comparison)
- 逻辑操作符(Logical)
- 位操作符(Bitwise)
3.2 算术操作符
let x = 10; let y = 3; console.log(x + y); console.log(x - y); console.log(x * y); console.log(x / y); console.log(x % y); console.log(x ** y); // increment console.log(++x); // first + then output console.log(x++); // output then + console.log(--x); // first - then output console.log(x--); // output then -
3.3 赋值操作符
let x = 10; x = x + 5; x += 5; x = x * 3; x *= 3;
3.4 比较操作符
let x = 1; console.log(x > 0); console.log(x >= 1); console.log(x < 1); console.log(x <= 1); console.log(x === 1); console.log(x !== 1);
3.5 等号运算符
// strict equality (same type and same value) console.log(1 === 1) // true console.log('1' === 1) // false // lose equality (check value only) console.log(1 == 1) // true console.log('1' == 1) // true console.log(true == 1) // true
3.6 三元运算符(Ternary Operator)
let points = 110; let type = points > 100 ? 'gold' : 'silver'; console.log(type);
3.7 逻辑运算符
Logical AND (&&) Logical OR (||) Logical NOT (!)
3.8 非布尔值逻辑运算
console.log(false || true); // true console.log(false || 'Mosh'); // Mosh console.log(false || 1); // 1 /* below are Falsy (false) values undefined null 0 false '' NaN (Not a Number) Anything that is not Falsy -> Truthy */
短路:
let userColor = 'red'; let defaultColor = 'blue'; let currntColor = userColor || defaultColor; console.log(currntColor); // red userColor = undefined; currntColor = userColor || defaultColor; console.log(currntColor); // blue
3.9 位操作符
- 1 = 00000001
- 2 = 00000010
- 3 = 00000011
And(&) Or(|),参看下面代码:
const readPermission = 4; const writePermission = 2; const execPermission = 1; let myPermission = 0; myPermission = myPermission | readPermission | writePermission | execPermission; let message = myPermission & readPermission ? 'yes' : 'no'; console.log(message)
3.10 运算优先级
4 流程控制
4.1 if ... else
let hour = 10; if (hour > 6 && hour < 12) console.log('Good morning'); else if (hour >= 12 && hour < 18) console.log('Good afternoon'); else console.log('Good evening');
4.2 switch ... case
let role = 'moderator'; switch (role) { case 'guest': console.log('Guest User'); break; case 'moderator': console.log('Moderator User'); break; default: console.log('default user'); }
4.3 for loops
4.3.1 for
for (let i = 0; i < 5; i++) { console.log("Hello, World."); }
4.3.2 while
let i = 0; while (i < 5) { console.log(i); i++; }
4.3.3 do ... while
let i = 0; do { console.log(i); i++; } while (i < 5);
4.3.4 无限循环
do { console.log("xxx"); } while (true);
4.3.5 for ... in
const person = { name: 'jinyc', age: 20 }; for (let key in person) console.log(key, person[key]); let colors = ['red', 'green', 'blue']; for (let index in colors) console.log(index, colors[index]);
4.3.6 for ... of
let colors = ['red', 'green', 'blue']; for (let color of colors) console.log(color);
4.3.7 Max
function GetMax(num1, num2) { return (num1 > num2) ? num1 : num2; } console.log(GetMax(2, 5));
4.3.8 Landscape and Portrait
function isLandscape(width, height) { return (width > height); } console.log(isLandscape(500, 1000));
4.3.9 FizzBuzz
function fizzBuzz(input) { if (typeof input !== 'number') console.log(NaN); else if (input % 3 === 0 && input % 5 !== 0) console.log('Fizz'); else if (input % 3 !== 0 && input % 5 === 0) console.log('Buzz'); else if (input % 3 === 0 && input % 5 === 0) console.log('FizzBuzz'); else console.log(input); } fizzBuzz(15);
4.3.10 Check Speed
function checkSpeed(speed) { const speedLimit = 70; const kmPerPoint = 5; if (typeof speed !== 'number') return NaN; if (speed <= speedLimit) return 'OK' let points = Math.floor((speed - speedLimit) / kmPerPoint); if (points >= 12) return "suspended" else return points; } console.log(checkSpeed(60)); console.log(checkSpeed(80)); console.log(checkSpeed(60)); console.log(checkSpeed(120)); console.log(checkSpeed(140));
4.4 break and continue
done
4.5 Truthy & Falsy
以下是一些 falsy 值:
- underfined
- null
- ''
- false
- 0
- NaN
function countTruthy(array) { let cnt = 0; for (let v of array) if (v) cnt++; return cnt; } let a = [1, 2, 3]; console.log(countTruthy(a));
4.6 显示属性
let b = { name: 'jinzd', age: 40 }; function showProperties(s) { for (let key in s) console.log(key, s[key]); } showProperties(b);
上示例也可用于数组。
4.7 3和5倍数的和
console.log(sum(10)); function sum(limit) { let sum = 0; for (let i = 0; i <= limit; i++) if (i % 3 === 0 || i % 5 === 0) sum += i; return sum; }
4.8 成绩
const marks = [80, 80, 50]; console.log(calculateGrade(marks)); function calculateGrade(marks) { let avg = getAverage(marks); if (avg >= 90) return 'A'; if (avg >= 80) return 'B'; if (avg >= 70) return 'C'; if (avg >= 60) return 'D'; return 'F'; } function getAverage(array) { let sum = 0; let avg = 0; for (let value of array) sum += value; return sum / array.length; }
4.9 Starts
let cnt = 10; showStars(cnt); function showStars(cnt) { for (let i = 1; i <= cnt; i++) { let star = ''; for (let j = 1; j <= i; j++) star += '*'; console.log(star); } }
4.10 Prime Numbers 质数
showPrimes(200); function showPrimes(limit) { for (let number = 2; number <= limit; number++) { let isPrime = true; for (let factor = 2; factor < number; factor++) { if (number % factor === 0) { isPrime = false; break; } } if (isPrime) console.log(number); } }
5 对象 Objects
5.1 对象基础 Object Basics
// OOP const circle = { radius: 1, location: { x: 1, y: 1 }, isVisible: true, draw: function() { console.log('draw'); } }; circle.draw(); // method
5.2 工厂函数
function createCircle(radius) { return { radius, draw() { console.log("draw"); } }; } const circle1 = createCircle(1); console.log(circle1); circle1.draw(); const circle2 = createCircle(2); console.log(circle2); circle2.draw();
5.3 构造函数
使用 new 关键字
function Circle(radius) { this.radius = radius; this.draw = function() { console.log('draw'); } } const circle = new Circle(2); circle.draw();