【前端】javaScript

目录

JavaScript

什么是JavaScript

  • javaScript 是一门脚本语言

  • 遵从ECMAScript规范

  • 分为客户端JS和服务端JS

1、基础

1.1、变量

// 变量
// var 变量名 = "初始值"
var userName = "遇见星光";

console.log(userName); // 控制台输出

// 重新赋值,
userName = "yujianxingguang";

console.log(userName); // 控制台输出

1.1、常量

// 常量
// const 常量名 = 值
const FIVE_SECONDS = 5000;

// 常量的值是不允许更改的
// FIVE_SECONDS = 4000

1.1、基本数据类型

// 基本数据类型
var name; // name 为 undefined  ,未定义

var password = null; // null ,初始化了值,就是 null

var userName = "遇见星光"; // 字符串

var num = 1314; // 数字,数字类型可以带小数点,也可以不带:
var row = 14.14;

var visble = false; // 布尔 ,只有真和假(false/true
var isNum = true;

// 还有 数组、对象、函数

1.1、数据类型转换

1.1、注释

// 注释

// 单行注释

/*
多行注释
1
2
3
*/

/**
 * 文档注释
 *
 */

/**
 * 对两个参数操作进行加法运算
 * @param {number} a 第一个变量 
 * @param {number} b 第二个变量 
 * @returns 返回 两个变量之和
 */
function add(a, b) {
  return a + b;
}

add() // 调用函数

2、操作符

2.1、赋值操作符

// 赋值操作符  =
var x = 10;
var y = x;
console.log(x, y);

console.clear(); // 清空控制台

2.2、一元操作符

// 一元操作符
var num = -5;

var strNum = +"3";
console.log(strNum, typeof num); // 3 number

strNum++;
strNum--;
++strNum;
--strNum;

2.3、算数操符

// 算数操作符
console.log(1 + 10);
console.log(110 - 10);
console.log(110 * 10);
console.log(110 / 10);
console.log(99 % 9);
console.log(4 ** 2);

2.4、比较操作符

// 比较操作符
console.log(10 ### 5);
console.log(10 < 5);
console.log(10 >= 5);
console.log(10 <= 5);

console.log("5" == 5);
console.log(5 == 5);
console.log(10 === 5); // 类型也要相同

console.log(undefined == null);
console.log(undefined === null);

2.5、逻辑操作符

// 逻辑操作符
// false  =  false、0、""、null、undefined
console.log(true && true); // 逻辑与
console.log(true && false); //

console.log(true || true); // 逻辑或
console.log(true || false); //

console.log(!true); // 取反
console.log(!false);

console.log(false || "默认值"); // 短路特性
console.log(true || "默认值");

console.log(4);
console.log(!4);
console.log(!!4); // !!4  返回原来 4 所代表的的布尔值

2.6、位运算

// 位运算
// 5 101
// 3 011
console.log(5 & 3); // 与 有一个0 就是 0  001
console.log(5 | 3); // 或 有一个1 就是 1  111

console.log(5 ^ 3); // 异或 相同为 0 不同为 1  110
console.log(~5); // 取反 1=0,0=1;+1 取反 - 5+1

console.log(5 << 1); // << 左移  5:101   1010
console.log(5 >### 1); // >### 左移  5:101   10
console.log(-5 >>### 1); // >>### 无符号左移  5:101

2.7、三目运算

// 三目运算
// a>b ? "a":"b"
var temperature = 10;
console.log(temperature ### 15 ? "出门" : "在家");

3、流程控制

  • 语句块
  • if……else
  • if……else if……else
  • switch……case
  • while
  • do……while
  • for
  • break和continue

3.1、语句块

// 语句块
{
  var UserName = "遇见星光";
  console.log(UserName);

  let age = 18;

  const YEAR = 2021;
}

console.log(UserName); // 遇见星光
// console.log(age); // 未定义
// console.log(YEAR); // 未定义

3.2、if……else

// if……else
var passcode = prompt("请输入密码");
if (passcode == 123456) {
  console.log("登录成功");
} else {
  console.log("登录失败");
}

4.3、if……else if……else

// if……else if……else
var user = prompt("请输入用户名");
if (user == "admin") {
  console.log("超级管理员");
} else if (user == "root") {
  console.log("普通管理员");
} else {
  console.log("普通用户");
}

3.4、switch……case

// switch……case
var role = prompt("请输入权限");
switch (role) {
  case "admin":
    console.log("超级管理员");
    break;
  case "root":
    console.log("管理员");
    break;
  default:
    console.log("普通用户");
}

3.5、while

// while
var password = "";
while (password !== "123456") {
  password = prompt("输入密码");
}

3.6、do……while

// do……while
var x = 5;
do {
  console.log(x++);
} while (x ### 5 && x <= 10);

3.7、for

// for
for (let i = 0; i < 10; i++) {
  console.log(i);
}

3.8、break和continue

// break和continue
for (let i = 0; i < 10; i++) {
  if (i == 5) {
    continue; // 跳过 当先,进行下一次
  }
  console.log(i);
}

for (let i = 0; i < 10; i++) {
  if (i == 5) {
    break; // 跳出循环,停止
  }
  console.log(i);
}

4、函数

4.1、声明函数

// 声明函数
function run() {
  console.log("打开冰箱门");
  console.log("把大象放进去");
}

function run2(str) {
  console.log("打开冰箱门");
  console.log("把" + str + "放进去");
}

function numTest(num) {
  if (num < 0) return;
  return num + 10;
}

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

4.2、调用函数

// 调用函数
run();
run2("西瓜");
var num = numTest(5);
num = addNum(5, 5);
num = addNum(numTest(10), 5);

4.3、函数表达式

// 函数表达式
console.log(addNum);
var plus = addNum;
plus(10, 5);

// 匿名函数
var multiply = function (a, bparams) {
  console.log(a * b);
};

4.4、变量和函数提升(hoisting)

// 变量和函数提升(hoisting)
x = 5; // 使用前赋值

console.log(x);

var x;

divide(5, 4);

function divide(a, b) {
  console.log(a * b);
}

4.5、默认参数

// 默认参数
greetings();
greetings("张三");

function greetings(name = "遇见星光") {
  console.log("你好" + name);
}

login(undefined, "123456");

function login(name = "遇见星光", password) {
  console.log("你好" + name);
  console.log(password);
}

4.6、递归

// 递归
console.log(sum(100));

function sum(n) {
  if (n === 1) {
    return 1;
  }
  return n + sum(n - 1);
}

console.log(fib(5));

function fib(num) {
  if (num < 1) {
    return 1;
  }
  return fib(num - 1) + fib(num - 2);
}

4.7、arguments

// arguments
log("a01", "a02");
log("a01", "a02", "a03");

function log() {
  for (let i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

4.8、作用域

// 作用域
var x = 5; // 全局
function add(a) {
  console.log(a + x);
}

add(10);

4.9、var/let区别

// var/let区别
var z = 6;
if (z ### 2) {
  console.log(z);
  var num = 17;
}
console.log(num);

4.10、箭头函数

// 箭头函数
var greeting01 = () =### {
  console.log("Hello");
};
var greeting02 = (userName) =### {
  console.log("Hello" + userName);
};
var greeting03 = (userName, password) =### {
  console.log("Hello" + userName + password);
};

greeting01();
greeting02("遇见星光");
greeting03("admin", "12456");

var increment = (x) =### x * 2;
console.log(increment(10));

4.11、闭包

// 闭包
function squareSum(a, b) {
  function square(x) {
    return x * x;
  }

  return square(a) + square(b);
}

console.log(squareSum(5, 5));

function person() {
  let name = "遇见星光";
  function getName() {
    return name;
  }
  return getName;
}

var userName = person();
console.log(userName);
userName = userName();
console.log(userName);

4.12、柯里化

// 柯里化
function addThreeNums(a, b, c) {
  return a + b + c;
}
console.log(addThreeNums(5, 8, 10));

// 柯里化函数
function addThreeNumsCurry(a) {
  return function (b) {
    return function (c) {
      return a + b + c;
    };
  };
}
addThreeNumsCurry(1)(2)(3);

var fixedTwo = addThreeNumsCurry(5)(5); // 把前两个参数保存
fixedTwo(10); // 第三个参数 return 5 + 5 + 10;
fixedTwo(20); // 第三个参数 return 5 + 5 + 20;

4.13、自执行函数

// 自执行函数
var num1 = 10;
(function () {
  var num1 = 20;
  console.log(num1); // 20
})();
console.log(num1); // 10

4.14、回调函数

// 回调函数
function request(cd) {
  console.log("请求数据");
  cd("success"); // 回调函数
  console.log("请求结束");
}

// function callback(result) {
//   console.log("执行回调函数");
//   console.log("执行结果 : " + result);
// }

// request(callback);

request((result) =### {
  console.log("执行回调函数");
  console.log("执行结果 : " + result);
});

5、数组

5.1、创建数组

// 创建数组
var arr1 = [1, 2, 3];
console.log(arr1);

var arr2 = new Array(4, 5, 6);
console.log(arr2);

var arr3 = Array(7, 8, 9);
console.log(arr3);

var arr4 = Array.of(10, 11, 12);
console.log(arr4);

var arrSingle = Array(6);
console.log(arrSingle);

var arrSingle2 = new Array(7);
console.log(arrSingle2);

var arrSingle3 = Array.of(4);
console.log(arrSingle3);

var arrSingle4 = [9];
console.log(arrSingle4);

5.2、访问数组

// 访问数组
var arr = [1, 2, 3];
console.log(arr.length);
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);

5.3、添加元素

// 添加元素
var arr = [1, 2, 3];

arr[0] = 4;
console.log(arr);

arr[3] = 5;
console.log(arr);

arr[9] = 5;
console.log(arr);

5.4、删除元素

// 删除元素
var arr = [1, 2, 3];
console.log(arr);

arr.length = 2;
console.log(arr);

arr.length = 0;
console.log(arr);

var arr = [1, 2, 3, 4, 5, 6];
console.log(arr);

arr.splice(2, 1); //arr.splice(索引, 删除元素个数)
console.log(arr);

arr.splice(1, 2, 3, 7, 8); // arr.splice(索引, 删除元素个数,索引后面添加,7 ,8 , )
console.log(arr);

arr.splice(1, 0, 9, 10); // 0 :索引后面添加
console.log(arr);

5.5、数组遍历

// 数组遍历
var arr = [1, 2, 3, 4, 5, 6, 7];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

console.log("for  of");
for (const ele of arr) {
  console.log(ele);
}

arr.forEach((ele, index, self) =### {
  // 元素,索引,元素本身
  console.log(ele, index, self);
});

5.6、栈模式

// 栈模式
var stack = [1, 2, 3, 4, 5, 6];

stack.push(7); // 添加元素
console.log(stack);

stack.push(8, 9, 10);
console.log(stack);

var last = stack.pop(); // 弹出最后一个元素,返回元素的值
console.log(stack);
console.log(last);

console.log(stack[stack.length - 1]);

console.clear();

5.7、队列模式

// 队列模式
var queue = [1, 2, 3];
queue.push(4, 5, 6);
console.log(queue);

var first = queue.shift(); // 弹出第一个元素,返回元素的值
console.log(queue);
console.log(first); // 1

queue.unshift(11, 12, 13); // 数组头部添加元素
console.log(queue);

5.8、反转数组

// 反转数组
var arr = [1, 2, 3, 4, 5, 6];
console.log(arr.reverse()); // 反转数组,返回并改变了数组
console.log(arr);

console.log("hello".split("").reverse().join()); // .split("") 分割字符串

5.9、数组排序

// 数组排序
var arr = [1, 4, 54, 12, 41, 1, 4, 741, 45];
arr.sort();
console.log(arr.sort());
console.log(arr);

// 自定义降序
arr.sort((a, b) => {
  if (a > b) {
    return -1;
  } else if (a < b) {
    return 1;
  } else {
    return 0;
  }
});

console.log(arr);

5.10、数组连接

// 数组连接
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
console.log(arr1.concat(arr2));

5.11、数组裁切

// 数组裁切
var arr = [1, 2, 3, 4, 5, 6];

console.log(arr.splice(1));
console.log(arr.splice(1, 4));
console.log(arr.splice(1, -1));

5.12、map数组

// map数组
var arr = [1, 2, 3, 4];
var mappedArr = arr.map((eml) =### eml * 2);
console.log(arr);
console.log(mappedArr);

5.13、reduce数组

// reduce数组
var arr = [1, 2, 3, 4, 5, 6];
var result = arr.reduce((previous, current) =### previous + current, 5); // 5 初始值
console.log(result);

var result = arr.reduce((previous, current) =### previous + current);
console.log(result);

5.14、数组过滤

// 数组过滤
var arr = [1, 2, 3, 4, 5, 6];
var filterredArr = arr.filter((item) =### item ### 4);
console.log(filterredArr);

5.15、数组测试

// 数组测试
var arr = [1, 2, 3, 4, 5, 6];

var result = arr.every((item) =### item ### 5); // 判断所有元素 有一个为假,数组为假
console.log(result);

var result = arr.some((item) =### item ### 5); // 判断元素,有一个为真,数组为真
console.log(result);

5.16、destructuring解构操作符

// destructuring 解构操作符
var arr = [1, 2, 3];
var [a, b, c] = arr;
console.log(a);
console.log(b);
console.log(c);

var user = ["admin", "123456", 18];
var [userName, password] = user;
console.log(userName, password);

var user = ["root", "123456", 18];
var [userName, , age] = user;
console.log(userName, age);

function multipleReturns() {
  let userName = "遇见星光";
  let positon = "学员";

  return [userName, positon];
}

var [myName, myPositon] = multipleReturns();
console.log(myName, myPositon);

5.17、rest 操作符

// rest操作符
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var [a, b, ...rest] = arr;
console.log(a, b, rest);

var [a, , b, ...rest] = arr;
console.log(a, b, rest);

function variousArr(...args) {
  console.log(args);
}

variousArr(1, 2, 3, 4);

5.18、多维数组

// 多维数组
var arr = [];

for (let i = 0; i < 5; i++) {
  arr[i] = [];
  for (let j = 0; j < 4; j++) {
    arr[i][j] = i + j;
  }
}

console.log(arr);

6、对象

6.1、创建对象

// 创建对象
var employee = {
  name: "张三",
  age: 18,
  posotion: "学员",
  singIn: function () {
    console.log("张三打卡");
  },
};

var employee2 = new Object();
employee2.name = "李四";
employee2.age = 18;
employee2.singIn = function () {
  console.log("李四打卡");
};

6.2、对象属性

// 对象属性
console.log(employee.name);
console.log(employee["name"]);

employee.name = "王五";
console.log(employee.name);

employee["name"] = "张三";
console.log(employee.name);

employee.sex = "male";
console.log(employee.sex);

employee3 = {
  name: "王五",
  "birth-date": "2021-09-01",
  birthDate: "2021-09-01",
};

console.log(employee3["birth-date"]);
console.log(employee3.birthDate);

6.3、省略key

// 省略key
var name = "李四";
var employee4 = {
  name,
  singIn() {
    console.log("李四打卡");
  },
};

console.log(employee4.name);
console.log(employee4.singIn);

6.4、遍历对象属性

// 遍历对象属性
console.log(Object.keys(employee4));
for (const key in employee4) {
  console.log(key);
}

6.5、删除对象属性

// 删除对象属性
delete employee4.name;
console.log(Object.keys(employee4));

6.6、构造函数

// 构造函数
function Employee(name, position) {
  this.name = name;
  this.position = position;
}

var empl1 = new Employee("遇见星光", "学员");
console.log(empl1);

6.7、this

// this
var empl2 = {
  name: "李四",
  position: "后端工程师",
  signIn() {
    console.log(this.name + "上班打卡");
  },
};

empl2.signIn();

empl2.goToWord = function () {
  console.log(this.name + "去上班");
};
empl2.goToWord();

empl2.goToWord = () =### {
  console.log(this.name + "去上班");
};
empl2.goToWord();

6.8、getters和seters

// getters和seters
var person = {
  fistName: "三",
  lastName: "张",
  get fullName() {
    return this.lastName + this.fistName;
  },
  set fullName(fullName) {
    console.log(fullName);
    [this.lastName, this.fistName] = fullName.split(",");
  },
};

console.log(person.fullName);

person.fullName = "李,四";
console.log(person.fullName);
console.log(person.lastName, person.fistName);

// 构造函数
function Employee(name, position) {
  this.name = name;
  this.position = position;
}

var empl3 = new Employee("遇见星光", "学员");

// 给构造函数 添加 get set:defineProperty(需要添加的对象,"key",{get,set})
Object.defineProperty(empl3, "userInfo", {
  get: function () {
    return this.name + " " + this.position;
  },
  set: function (userInfo) {
    [this.name, this.position] = userInfo.split(" ");
  },
});

console.log(empl3.name, empl3.userInfo);

empl3.userInfo = "遇见星光 后端工程师";
console.log(empl3.name, empl3.userInfo);

6.9、原型

// 原型
function Employee(name, position) {
  this.name = name;
  this.position = position;
  this.singIn = function () {
    console.log(this.name + "打卡");
  };
}

var empl1 = new Employee("张三", "前端工程师");
var empl2 = new Employee("李四", "后端工程师");

console.log(empl1);
console.log(empl2);

// 函数
console.log(Employee.prototype);

// 增加属性
Employee.prototype.age = 20;

console.log(empl1.age);
console.log(empl2.age);

// 增加方法
Employee.prototype.printInfo = function () {
  console.log(this.name, this.age, this.position);
};

empl1.printInfo();
empl2.printInfo();

// 对象 prototype
console.log(empl1.__proto__);
console.log(empl1.__proto__ === Employee.prototype); // true

console.log(Object.getPrototypeOf(empl2));

console.clear();

6.10、object.create()

// object.create()
console.log(empl1);

for (const key in empl1) {
  console.log(key);
}

//
var manager = Object.create(empl1);
console.log(manager);
console.log(manager.name, manager.position);

manager.name = "李四";
manager.position = "产品经理";
manager.printInfo();

console.log(Object.getPrototypeOf(manager));

6.12、原型链

// 原型链
var protoOfManager = Object.getPrototypeOf(manager);
console.log(protoOfManager);

var protoOfEmpl1 = Object.getPrototypeOf(protoOfManager);
console.log(protoOfEmpl1);

var protoOfEmpl = Object.getPrototypeOf(protoOfEmpl1);
console.log(protoOfEmpl);

var protoOfObject = Object.getPrototypeOf(protoOfEmpl);
console.log(protoOfObject);

console.log(Object.getPrototypeOf(Object));

console.log(manager.toString);
console.log(manager.toString());

6.13、修改原型指向

// 修改原型指向
function Manager() {}

Manager.prototype.department = "技术部";

Object.setPrototypeOf(manager, Manager.prototype);
console.log(manager.department);

6.14、spread 操作 解构

// spread操作符   解构
var post = {
  id: 1,
  title: "JavaScript",
  content: "对象",
};

console.log(post);

var postClone = { ...post }; // 克隆
console.log(postClone);

console.log(post === postClone);

var post2 = {
  ...post,
  author: "遇见星光",
};
console.log(post2);

var arr = [1, 5, 9];
var arrClone = [...arr, 3, 5, 7];

console.log(arr);
console.log(arrClone);

function savePost(id, title, content) {
  console.log("文章 : ", id, title, content);
}
savePost(...[1, "Java", "从入门到放弃"]);

6.15、destructuring&rest

// destructuring & rest
var { id, title } = post;
console.log(id, title);

var { id, title: headline } = post;
console.log(id, headline);

// 添加默认值
var { id, title, comments = "没有评论" } = post;
console.log(id, title, comments);

var [a, b = 2] = [1];
console.log(a, b);

var post3 = {
  id: 1,
  title: "JavaScript",
  content: "对象",
  comments: [
    {
      userId: 1,
      comment: "评论1",
    },
    {
      userId: 2,
      comment: "评论2",
    },
    {
      userId: 3,
      comment: "评论3",
    },
    {
      userId: 4,
      comment: "评论4",
    },
  ],
};

var {
  comments: [, { comment }],
} = post3;
console.log(comment);

function getId(idKey, obj) {
  let { [idKey]: id } = obj;
  return id;
}
console.log(getId("userId", { userId: 3 }));

var { comments, ...rest } = post2;
console.log(rest);

function savePostObject(id, title, content, ...rest) {
  console.log("文章 : ", id, title, content);
  console.log(rest);
}
savePostObject({
  id: 4,
  title: "java",
  content: "从入门到放弃",
  author: "遇见星光",
});

6.16、值传递与引用传递

// 值传递与引用传递
function byReference(arr) {
  arr[0] = 5;
}
var array = [1, 2, 3];
byReference(array);
console.log(array);

function byReferenceObj(obj) {
  obj.title = "默认标题";
}
var post = { id: 1, title: "标题" };
byReferenceObj(post);
console.log(post);

function byReferenceStr(str) {
  str = "abc"; // 创建一个新的变量,不改变原有的
}
var testStr = "testStr";
console.log(testStr);

function byValue(num) {
  num = 100;
  console.log(num);
}
var testNum = 10;
byValue(testNum);
console.log(testNum);

6.17、call & apply & bind

// call & apply & bind
// 改变this指向
var empl = {
  id: 1,
  name: "遇见星光",
  printInfo: function () {
    console.log("员工姓名 : ", this.name);
  },
  department: {
    name: "技术部",
    printInfo: function () {
      console.log("部门名称: ", this.name);
    },
  },
};

empl.printInfo();
empl.department.printInfo();

function printInfo(dep1, dep2, dep3) {
  console.log("员工姓名 : ", this.name, dep1, dep2, dep3);
}
printInfo("技术部", "IT 事业部", "后勤部");
printInfo.call(empl, "技术部", "IT 事业部", "后勤部"); // 绑定对象
printInfo.apply(empl, ["技术部", "IT 事业部", "后勤部"]);

var empPrinInfo = printInfo.bind(empl, "技术部", "IT 事业部", "后勤部");
console.log(empPrinInfo);

7、面向对象

7.1、定义class & 成员方法

// 定义class
class Employee2 {
  constructor(name, position) {
    this.name = name;
    this.position = position;
  }
  // 成员方法
  singIn() {
    console.log(this.name, "上课打卡");
  }

  set info(info) {
    [this.name, this.position] = info.split(" ");
  }

  get info() {
    return [this.name, this.position];
  }
}

var empl = new Employee2("遇见星光", "学员");
console.log(empl);
empl.singIn();

console.log(empl.info);

7.2、实现继承

// 实现继承
class Manager2 extends Employee2 {
  constructor(name, position, dept) {
    super(name, position);
    this.dept = dept;
  }
}
var manager = new Manager2("张三", "前端工程师", "技术部");
console.log(manager);

7.3、成员变量(新

// 成员变量(新
class Employee3 {
  dept = "";
  constructor(name) {
    this.name = name;
  }
}

var empl = new Employee3("张三");
console.log(empl);

empl.dept = "技术部";
console.log(empl);

7.4、静态成员

// 静态成员(新
class Page {
  static count = 0;
  static increaseViewCount() {
    Page.count++;
  }
}

Page.count++;
console.log(Page.count);

Page.increaseViewCount();
console.log(Page.count);

8、字符串

// 8.1、字符串定义与转义
var str = "hello";
console.log(str);

var str2 = new String("你好");
console.log(str2);

8.1、字符串定义与转义

// 转义
var str = 'TOM:"Hello"'; // "TOM:\"Hello\""
console.log(str);
console.log("Tom\n \t Hello");

console.log("\u4310");

8.2、字符串遍历

// 8.2、字符串遍历
var str = "字符串遍历";
for (let i = 0; i < str.length; i++) {
  console.log(str[i]);
}

for (let c of str) {
  console.log(c);
}

8.3、字符串裁剪

// 8.3、字符串裁剪
var str = "字符串裁剪";

console.log(str.slice(0, 2));
console.log(str.slice(3, 4));
console.log(str.slice(0, -1));
console.log(str.slice(-6, 1));

console.log(str.substring(0, 4));
console.log(str.substring(4));
console.log(str.substring(0, -1));

8.4、字符串拼接

// 8.4、字符串拼接
var str1 = "hello";
var str2 = "word";
console.log(str1 + str2);
console.log(str1.concat(str2));

8.5、大小写转换

// 8.5、大小写转换
var str = "helloword";
console.log(str.toLocaleUpperCase());
console.log(str.toUpperCase());

8.6、去除空格

// 8.6、去除空格 ,左右两边
var str = "  hello word  ";
console.log(str.trim());
console.log(str.trimLeft());
console.log(str.trimRight());

8.7、模板字符串

// 8.7、模板字符串
var str = "Hello Word ,Hi Tom";
var longStr = `Hello Word ,Hi 
Tom ${str}`;

console.log(str);
console.log(longStr);

function greeting(strings, gender) {
  console.log(strings, gender);
  var genderStr = "";
  if (gender === "M") {
    genderStr = "先生";
  } else if (gender === "F") {
    genderStr = "女士";
  }
  return `${strings[0]}${genderStr}`;
}

var gender = "M";
var result = greeting`你好 Tom ${gender}`;
console.log(result);

9、正则

9.1、创建正则表达式

// 1、创建正则表达式
var str = "where when what";

var re = /wh/g; // g 全局搜素
var re2 = new RegExp("wh");

console.log(re.exec(str)); // 返回 匹配到的值
console.log(re.exec(str)); // 返回 匹配到的值
console.log(re.test(str)); // 返回 布尔值

console.log(re2.exec(str));
console.log(re2.test(str));

9.2、字符匹配

// 2、字符匹配
var str = `this str contains 123
CAPITALIZED letter and _-&% symbols`;

console.log(/T/.test(str));
console.log(/this/.test(str));
console.log(/thiss/.test(str));
console.log(/12/.test(str));
console.log(/1234/.test(str));
console.log(/_-&/.test(str));

9.3、特殊字符匹配

// 3、特殊字符匹配
var str = `this str contains 123
CAPITALIZED letter and _-&% symbols`;

console.log(str.match(/th.s/g)); // g 全局匹配
console.log(str.match(/1.3/g));

console.log(str.match(/\d/g)); // \d 数字
console.log(str.match(/\w/g)); // \w 字母
console.log(str.match(/\s/g)); // \s 空格 ,换行符

console.log("你好".match(/\u4f60/g));

9.4、匹配次数

// 4、匹配次数
var str = `this str contains 123
CAPITALIZED letter and _-&% symbols`;

console.log(str.match(/this.*/g));
console.log(str.match(/t+/g));
console.log(str.match(/t?/g));

console.log(str.match(/t{2}/g));
console.log(str.match(/\d{1,}/g));

9.5、区间、逻辑和定界符

// 5、区间、逻辑和定界符
var str = `this str contains 123
CAPITALIZED letter and _-&% symbols`;

console.log(str.match(/[abc]/g));
console.log(str.match(/[^a-z]/g));
console.log(str.match(/this|contains/g));

var str = `this str contains this`;
console.log(str.match(/this/g));
console.log(str.match(/^this/g));
console.log(str.match(/this$/g));
console.log(str.match(/\bthis\b/g));

9.6、分组

// 6、分组
var str = `this that this and that`;
console.log(/(th).*(th)/.exec(str));

var str = `aaaab abb cdaa`;
console.log(str.match(/(aa){2}/g));

9.7、常见正则表达式

// 7、常见正则表达式
var mobileRe = /^1[3-9]\d{9}/g;
console.log(mobileRe.test("13345678911"));

var email = /^([a-zA-Z0-9_\-\.].+)@([a-zA-Z0-9_\-\.].+)/g;
console.log(email.test("1810689221@qq.com"));
console.log(email.test("1810689221@qq.com"));

9.8、字符串替换

// 8、字符串替换
var str = "This123 is 123an123 apple";
console.log(str.replace("This", "this"));
console.log(str.replace(/\d/g, ""));

var html = "<p>Hi <span>Tom</span> </p>";
console.log(html.replace(/(<[a-zA-Z]*>)|(<\/[a-zA-Z]*>)/g, ""));

9.9、字符串分割

// 9、字符串分割
var tags = "html, css, JavaScript";
console.log(tags.split(", "));

var str = "this | is , an & apple";
console.log(str.split(/\W+/g)); //  /W 非字母

10、内置对象

10.1、Number

// 1、Number
var strNum = "15";
var num = Number.parseInt(strNum);
console.log(strNum);
console.log(num);
console.log(typeof num);

var strNum = "13.14";
var num = Number.parseFloat(strNum);
console.log(num);
console.log(typeof num);

var strNum = "abc";
var num = parseInt(strNum);
console.log(num);
console.log(isNaN(num));

var num = 13.1414151461;
var numStr = num.toFixed(2); // 保留小数点后两位
console.log(numStr);

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MAX_VALUE);

console.log(Number.MIN_SAFE_INTEGER);
console.log(Number.NEGATIVE_INFINITY);

10.2、Math

// 2、Math
console.log(Math.PI);
console.log(Math.abs(-6));
console.log(Math.sin(Math.PI / 2));
console.log(Math.floor(3.14));
console.log(Math.ceil(3.14));
console.log(Math.pow(10, 2));
console.log(Math.trunc(10.2));
console.log(Math.trunc(10.8));

console.log(Math.random());
console.log(Math.ceil(Math.random() * 1000));
console.log(Math.trunc(Math.random() * 1000));

10.3、Date

// 3、Date
console.clear();
var date = new Date();
console.log(date);
console.log(date.getFullYear()); // 年
console.log(date.getMonth() + 1); //月
console.log(date.getDate()); // 日
console.log(date.getDay()); // 周几
console.log(date.getHours()); // 小时
console.log(date.getMinutes()); // 分
console.log(date.getSeconds()); // 秒
console.log(date.getTime()); // 时间戳

console.log(date.toLocaleTimeString()); //
console.log(date.toLocaleDateString()); //

date.setFullYear(2022);
console.log(date.toLocaleDateString());

date.setTime(1630662363092);
console.log(date.toLocaleDateString());

10.4、Json对象介绍

// 4、Json对象介绍
var postJSON = `{
  "id": 1,
  "title": "JavaScript",
  "comments": [
    {
      "userId": 1,
      "comment": "从入门到放弃"
    },
    {
      "userId": 2,
      "comment": "从入门到放弃"
    },
    {
      "userId": 3,
      "comment": "从入门到放弃"
    }
  ],
  "published": true,
  "author": null
}`;

console.log(JSON.parse(postJSON)); // json 转 对象

var person = {
  id: 1,
  name: "遇见星光",
  skills: ["Java", "HTML"],
};

console.log(JSON.stringify(person, null, 2)); // 对象 转 json

var comments = `[
  {
    "id": 1,
    "name": "遇见星光",
    "skills": [
      "Java",
      "HTML"
    ]
  }
]`;
console.log(JSON.parse(comments));

10.5、Set

// 5、Set  元素不能重复
var set = new Set();
set.add(1);
set.add(5);
set.add(9);
set.add(10);
console.log(set);

set.add(5);
console.log(set);

console.log(set.has(4));
console.log(set.has(5));

set.forEach((value) => {
  console.log(value);
});

set.delete(5); // 删除
console.log(set);

set.clear(); // 清空
console.log(set);

var obj1 = { id: 1 };
var obj2 = { id: 2 };
var obj3 = { id: 2 };

set.add(obj1);
set.add(obj2);
set.add(obj3);
console.log(set);

10.6、Map

// 6、Map
var map = new Map();
map.set("id", 1);
map.set("name", "遇见星光");

console.log(map);

console.log(map.get("id"));
console.log(map.has("id"));

// 遍历
map.forEach((key, value) => {
  console.log(key, value);
});

var iterator = map.entries();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());

for (let [key, value] of map) {
  console.log(key, value);
}

// 删除
map.delete("id");

for (let [key, value] of map) {
  console.log(key, value);
}

11、异常

11.1、异常介绍

// 1、异常介绍
// console.log(a);

// console.log("这行不会执行");
// var emp = undefined;
// console.log(emp);
// console.log(emp.name);

11.2、捕获异常

// 2、捕获异常
try {
  console.log(a);

  var emp = undefined;
  console.log(emp);
  console.log(emp.name);
} catch (err) {
  console.log(err);
} finally {
  console.log("总会执行");
}
console.log("这行会执行");

11.3、throw抛出异常

// 3、throw抛出异常
function fethDate() {
  console.log("获取数据……");
  throw 404;
}

try {
  fethDate();
} catch (e) {
  if (e === 404) {
    console.error("未查询到数据");
  }
}

11.4、Error对象

// 4、Error对象

// 自定义 错误
class ApiError extends Error {
  constructor(url, ...params) {
    super(...params);
    this.url = url;
    this.name = "ApiError";
  }
}

function fethDate() {
  console.log("获取数据……");
  throw new ApiError("/post", "404");
}

try {
  fethDate();
} catch (error) {
  console.log(error);
  console.error(error.name);
  console.error(error.message);
}

11.5、捕获多个异常

// 5、捕获多个异常
function fethDate() {
  console.log("获取数据……");
  console.log(a);
  throw new ApiError("/post", "404");
}

try {
  fethDate();
} catch (error) {
  if (error instanceof ReferenceError) {
    console.error("程序异常");
  } else if (error instanceof ApiError) {
    console.error("Api 异常");
  }
}

12、异步

12.1、setTimeout

// 1、setTimeout
console.log("第一行代码");

var timer1 = setTimeout(() => {
  console.log("setTimeout() 一秒后执行");
}, 1000);

console.log("第二行代码");

setTimeout(() => {
  console.log("timer1:", timer1);
  clearTimeout(timer1);
  console.log("中断了 timer1 的执行");
}, 500);

12.2、setInterval

// 2、setInterval
var interval = setInterval(() => {
  let date = new Date();
  console.log(`${date.getHours()}:${date.getHours()}:${date.getSeconds()}`);
}, 1000);

setTimeout(() => {
  console.log("interval", interval);
  clearInterval(interval);
  console.log("停止了 tinterval");
}, 5000);

12.3、创建promise

// 3、创建 promise
var promise = new Promise((resolve) => {
  setTimeout(() => {
    resolve("执行成功");
  }, 2000);
});

12.4、promise完成回调

// 4、promise 完成回调
var promise = new Promise((resolve) => {
  setTimeout(() => {
    resolve("执行成功");
  }, 2000);
});

promise.then((value) => {
  console.log(value);
});

12.5、promise异常捕获

// 5、promise 异常捕获
var promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    // resolve("执行成功");
    reject("执行失败");
  }, 2000);
});

promise.catch((error) => {
  console.error(error);
});

12.6、promise链式调用

// 6、promise 链式调用
new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(1);
  }, 1000);
})
  .then((value) => {
    console.log(value);
    return value + 10;
  })
  .then((value) => {
    console.log(value);
    return new Promise((resolve) => resolve(value + 20));
  })
  .then((value) => {
    console.log(value);
  });

new Promise((resolve, reject) => {
  setTimeout(() => {
    // resolve(1);
    reject("失败");
  }, 1000);
})
  .then((value) => {
    console.log(value);
    return value + 10;
  })
  .then((value) => {
    console.log(value);
    return new Promise((resolve) => resolve(value + 20));
  })
  .then((value) => {
    console.log(value);
  })
  .catch((error) => {
    console.error(error);
  });

12.7、多个promise同时执行

// 7、多个 promise 同时执行
var p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(1);
  }, 1000);
});
var p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(2);
  }, 2000);
});
var p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(3);
  }, 3000);
});

// 同时执行多个,并返回 Promise对象
Promise.all([p1, p2, p3]).then((value) => {
  console.log(value);
});

12.8、async & await

// 8、async & await
// async function async1() {
//   setTimeout(() => {
//     console.log("async1 执行完毕");
//   }, 1000);
// }

async function async2() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(10);
    }, 1000);
  });
}
async function async3() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // resolve(100);
      reject("async3() 执行出错");
    }, 1000);
  });
}

async function async1() {
  let result2 = await async2();
  console.log("result2 :", result2);
  try {
    let result3 = await async3();
  } catch (error) {
    console.log(error);
  }

  console.log("result3 :", result3);
}

async1();
// console.log("async1 :", async1()); // Promise 对象

13、模块化

13.1、导出模块

// 1、export 导出模块
/**
 *
 * @param {Date} date
 * @returns
 */
export function formatDate(date) {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

export const DAYS_OF_YEAR = 365;
/**
 *
 * @param {Date} date
 * @returns
 */
function formatDate(date) {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

const DAYS_OF_YEAR = 365;
// 命名方式导出
export { formatDate, DAYS_OF_YEAR }

13.2、导入模块

<script src="./12-模块化.js" type="module"></script>
import { formatDate, DAYS_OF_YEAR } from "./modules/utils.js";
console.log(formatDate(new Date()));

console.log(DAYS_OF_YEAR);

13.3、默认导出

/**
 *
 * @param {Date} date
 * @returns
 */
function formatDate(date) {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

const DAYS_OF_YEAR = 365;

export default formatDate; // 默认导出

导入

import formatDate from "./modules/utils.js";
console.log(formatDate(new Date()));

13.4、别名导入

import formatDate, { DAYS_OF_YEAR as DAYS } from "./modules/utils.js";
console.log(formatDate(new Date()));
console.log(DAYS);
import * as utils from "./modules/utils.js";
console.log(utils.formatDate(new Date()));
console.log(utils.DAYS_OF_YEAR);
/**
 *
 * @param {Date} date
 * @returns
 */
function formatDate(date) {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

const DAYS_OF_YEAR = 365;

export { formatDate, DAYS_OF_YEAR };

14、总结

14.1、总结

  • 语法灵活
  • 避免争议
    • var
  • 多种范式

14.2、下一步

  • web api
  • DOM 操作
  • 存储 api
    • localstorage
  • 地理api
    • geolocation
  • 前端框架
    • vue
    • react
  • 后端
posted @ 2021-09-04 18:57  遇见星光  阅读(49)  评论(0编辑  收藏  举报