javaScript基础语法

javaScript基础语法

函数

箭头函数
  • 多种写法
let add = (x, y) => { // 常规写法
return x + y;
}
let sum = add(3, 4);
console.log(sum);
//省略return和大括号
let add = (x, y) => x + y;
let sum = add(3, 4);
console.log(sum); // 输出7
// 省略小括号、return和大括号
let square = x => x * x;
let result = square(3);
console.log(result); // 输出9
let hello = () => { // 不能省略小括号
console.log("Hello, World!");
}
hello(); // 输出Hello, World!
// 返回对象不能省略大括号和return
let s = () => {return {name: 'Alice'}}
// 用小括号代替大括号可省略return
let s = () => ({name: 'Alice'})
嵌套函数
  • 函数中的函数
function distance(x1, y1, x2, y2) {
// square函数的作用域被限定在distance函数之内
function square(x) {
return x * x;
}
return Math.sqrt(square(x2 - x1) + square(y2 - y1));
}
let dist = distance(0, 0, 3, 4);
console.log(dist); // 输出5
闭包
  • 函数外部无法访问函数内部定义的局部变量
unction counter() { let count = 0; // 定义局部变量 }console.log(count); // 错误,count没有定义 console.log(counter.count); // 输出undefined
  • 利用返回值获取函数内部变量的值
function counter() {
let count = 0;
function addOne() {
return ++count;
}
return addOne; // 将嵌套函数作为返回值
}
let result = counter(); // result接收counter函数的返回值addOne函数
console.log(result()); // 输出1
console.log(result()); // 输出2,实现了计数功能
result = null; // 销毁闭包
  • 本质:将函数做为返回值
回调
  • 作为参数传入另一个函数的函数
function sayHello(sname) {
console.log("Hello," + sname + "!");
}
function execute(sname, callback) {
callback(sname);
}
execute('Alice', sayHello); // 输出Hello, Alice!
  • 使用匿名函数做为回调
function execute(sname, callback) {
callback(sname);
}
// 调用execute函数时传入匿名函数作为参数
execute('Alice', function(sname) {
console.log("Hello," + sname + "!");
}); // 
  • 本质是使程序动态灵活
默认参数
function add(a = 0, b = 0) {
return a + b;
}
console.log(add(1)); // 输出1
console.log(add(1, 2)); // 输出3
arguments
  • 数组元素个数
function sum() {
let result = 0;
for(let i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
console.log(sum(1, 2, 3, 4)); // 输出10
console.log(sum(1, 2, 3, 4, 5)); // 输出15

数组

数组的创建和使用
let names = ['Alice','Bob','Tom']; // 创建数组
console.log(names.length); // 打印数组长度 输出3
console.log(names.toString()); // 遍历数组 输出Alice,Bob,Tom
console.log(names.join(' - ')); // 输出Alice - Bob - Tom
console.log(names[2]); // 输出Tom
names[2] ='Trump'; // 修改数组中的元素
console.log(names.toString()); // 输出Alice,Bob,Trump
names[3] ='Jack'; // 增加一个数组元素 不会溢出
console.log(names.toString()); // 输出Alice,Bob,Trump,Jack
console.log(names.pop()); // 删除并输出Jack
console.log(names.toString()); // 输出Alice,Bob,Trump
names.push('Rose'); // 向数组末尾增加一个元素
console.log(names.toString()); // 输出Alice,Bob,Trump,Rose
names.shift(); // 删除数组中的第一个元素
console.log(names.toString()); // 输出Bob,Trump,Rose
names.unshift('Alice'); // 向数组首增加一个元素
console.log(names.toString()); // 输出Alice,Bob,Trump,Rose
console.log(names.indexOf('Bob')); // 输出1
names.push('Bob');
console.log(names.toString()); // 输出Alice,Bob,Trump,Rose,Bob
console.log(names.lastIndexOf('Bob')); // 输出4
let names1 = names.slice(0, 1);
console.log(names1.toString()); // 输出Alice
let names2 = names.slice(2, 4);
console.log(names2.toString()); // 输出Trump,Rose
let names3 = names1.concat(names2);
console.log(names3.toString()); // 输出Alice,Trump,Rose
  • 调用的是方法
数组的元素类型可以不同
let arr = [3, 5,'2', 9, false];
for(let item of arr) {
console.log(item);
}//合法数组
  • 注意!java、C语言中数组的元素类型必须相同
forEach方法
  • 遍历数组元素
let numbers = [3, 5, 2, 9, 6];
numbers.forEach(callback);
function callback(value, index, array) {
console.log(index + ' : ' + ++value);
}//遍历数组 value+1  forEach回调
filter方法
  • 过滤数组中的元素
  • 返回符合条件的新数组,方法不会更改原始数组
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定过滤规则的函数
function test(value, index, array) {
return value % 3 === 0; // 返回布尔值
}
console.log(numbers.toString()); // 输出3,5,2,9,6
console.log(numbers.filter(test).toString()); // 输出3,9,6
console.log(numbers.toString()); // 输出3,5,2,9,6
every方法
  • 测试数组中全部元素,返回布尔值
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定测试规则的函数
function test(value, index, array) {
return value > 5;
}
let result = numbers.every(test);
console.log(result); // 输出false
some方法
  • 测试数组中某些元素,返回布尔值
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定测试规则的函数
function test(value, index, array) {
return value > 5;
}
let result = numbers.some(test);
console.log(result); // 输出true
find方法
  • 返回符合测试函数的第一个数组元素的值
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定测试规则的函数
function test(value, index, array) {
return value > 4;
}
let result = numbers.find(test);
console.log(result); // 输出5
findIndex方法
  • 返回符合测试函数的第一个数组元素的索引
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定测试规则的函数
function test(value, index, array) {
return value > 4;
}
let result = numbers.findIndex(test);
console.log(result); // 输出1
map方法
  • 通过对每个数组元素执行函数后返回新数组
  • 方法不会更改原始数组
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定map规则的函数
function square(value, index, array) {
return value * value;
}
console.log(numbers.toString()); // 输出3,5,2,9,6
console.log(numbers.map(square).toString()); // 输出9,25,4,81,36
console.log(numbers.toString()); // 输出3,5,2,9,6
reduce方法
  • 通过对每个数组元素从左到右依次执行函数
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定reduce规则的函数
function sub(total, value, index, array) {
return total - value;
}
let result = numbers.reduce(sub);
console.log(result); // 输出-19
reduceright方法
  • 通过对每个数组元素从右到左依次执行函数
let numbers = [3, 5, 2, 9, 6];
// 定义一个确定reduce规则的函数
function sub(total, value, index, array) {
return total - value;
}
let result = numbers.reduceRight(sub);
console.log(result); // 输出-13
数组排序
  • 为sort方法提供一个比较函数实现排序
let numbers = [3, 5, 2, 9, 6];
numbers.sort(function(a, b) {
return b - a; // a - b为升序,b - a 为降序
});// 类比java的Comparable接口
console.log(numbers.toString()); // 输出9,6,5,3,2
  • 数组元素类型比较复杂时,用比较函数确定排序规则
team.sort(function(a, b) {
return a.age - b.age;
});
console.log(team);
let team = [ {
sname: 'Alice',
age: 19
}, {
sname: 'Bob',
age: 18
}, {
sname: 'Tom',
age: 20
},
];
多维数组
  • 数组的元素还是数组
let table = [];
for(let row = 0; row < 9; row++) {
table[row] = new Array(row);
for(let col = 0; col <= row; col++) {
table[row][col] = (row + 1) * (col + 1);
}
}
for(let i = 0; i < table.length; i++) {
console.log(table[i].toString());
}

对象

对象的创建与使用
let student = {
sid: '1083710314',
sname: 'Alice',
sayHello: function() {
console.log("Hi, I am " + this.sname + "!");
},
courses: {
c1: 'C',
c2: 'Java',
c3: 'JS'
}//也是对象
}
let student = {
sid: '1083710314',
sname: 'Alice',
sayHello: function() {
console.log("Hi, I am " + this.sname + "!");
},//student是具体的对象
courses: {
c1: 'C',
c2: 'Java',
c3: 'JS'
}//冒号左边是变量名,冒号右面可以是任意东西
}
// 输出Alice
console.log(student.sname);
// 输出Hi, I am Alice!
student.sayHello();
// 为student对象增加属性major
student.major ='CS';
// 输出CS
console.log(student.major);
// 输出 {c1: 'C', c2: 'Java', c3: 'JS'}
console.log(student.courses);
  • delete删除对象属性,in判断属性是否存在
let student = {
sid: '1083710314',
sname: 'Alice',
age: 18
}
console.log('age' in student); // 输出true
delete student.age;
console.log('age' in student); // 输出false
对象构造器
  • 可以构造类型相同的多个对象
  • jS没有类也可以构造对象
function Student(sid, sname) {
this.sid = sid;
this.sname = sname;
this.sayHello = function() {
console.log("Hi, I am " + this.sname + "!");
}//这个Student是类型,类型是function
}
let alice = new Student('1083710314','Alice');
let bob = new Student('1083710315','Bob');
// 输出Hi, I am Alice!
alice.sayHello();
// 输出Hi, I am Bob!
bob.sayHello();
// 为alice对象增加属性major
alice.major ='CS';
// 输出CS
console.log(alice.major);
// 输出undefined
console.log(bob.major);//bob没有专业
对象原型
  • 使用对象的prototype属性为对象构造器增加属性
function Student(sid, sname) {
this.sid = sid;
this.sname = sname;
}
let alice = new Student('1083710314','Alice');
let bob = new Student('1083710315','Bob');
Student.prototype.sayHello = function() { // 为对象原型增加属性
console.log("Hi, I am " + this.sname + "!")
}
alice.sayHello(); // 输出Hi, I am Alice!
bob.sayHello(); // 输出Hi, I am Bob!
对象解构赋值
let student = {
sid: '1083710314',
sname: 'Alice',
age: 18
}
let {sid, sname, age} = student//一一匹配
console.log(sid); // 输出1083710314
console.log(sname); // 输出Alice
console.log(age); // 输出18

类的定义和使用
  • 类代替了之前的对象构造器
class Student {
constructor(sid, sname, brithyear) {
this.sid = sid;
this.sname = sname;
this.brithyear = brithyear;
} // 构造器 数据成员
getAge() {
let date = new Date();
return date.getFullYear() - this.brithyear;
} // 方法 类型内部的函数叫方法
}
let alice = new Student('1083710314','Alice', 1990);
// 可以通过原型动态为类增加方法
Student.prototype.sayHello = function() {
console.log("Hi, I am " + this.sname + "!");
}
console.log(alice.getAge());// 输出31
alice.sayHello(); // 输出Hi, I am Alice!
私有成员和静态成员
  • 私有成员是以#开头
  • 静态成员通过static声明
class Student {
static #nextSid = 1; // jS定义静态私有字段不是用关键字而是用变量名规范
#sid = 0; // 私有字段必须在构造器外声明 赋初值
constructor(sname) {
this.#sid = this.#setNextSid(); // 通过this调用私有成员
this.sname = sname;//公有
}
getSid() { // 公有方法
return this.#sid;
}
#setNextSid() { // 私有方法
return Student.#nextSid++;
}//访问静态成员,通过类名就可以调用
static getNextSid() { // 静态公有方法
return Student.#nextSid; // 用类名调用静态私有成员
}
}
let alice = new Student('Alice');
let bob = new Student('Bob');
//console.log(alice.#sid); // 类外部无法访问私有字段
console.log(alice.getSid()); // 输出1 通过公有方法获取
console.log(alice.sname); // 输出Alice
console.log(bob.getSid()); // 输出2
console.log(Student.getNextSid()); // 输出3
//console.log(Student.#nextSid); // 类外部无法访问
Getter和Setter
  • 用get和set修饰
  • 像调用公有字段一样
class Student {
  #sname;
  #age;//都是私有的
  constructor(sname) {
	this.#sname = sname;
  }
  get sname() { // 定义公有Getter方法
	return this.#sname;
  }//get是关键字
  set sname(sname) { // 定义公有Setter方法
	this.#sname = sname;
  }
  get age() { // 定义公有Getter方法
	return this.#age;
  }
  set age(age) { // 定义公有Setter方法
	if(age > 0 && age < 150) // 对数据进行合法性验证
	  this.#age = age;
  }
}
let s = new Student('Alice');
console.log(s.sname);// 调用Getter方法,输出Alice
s.sname ='Bob'; // 调用Setter方法
console.log(s.sname);// 调用Getter方法,输出Bob
s.age = 18; // 调用Setter方法
console.log(s.age); // 输出18
s.age = 900; // 调用Setter方法
console.log(s.age); // 输出18
继承
class Person {
  #name; // Person类中定义的私有字段
  constructor(name) {
	this.#name = name;
  }//构造器
  get name() {
    return this.#name;
  }
  set name(name) {
	this.#name = name;
		}
  sayHello() {
	console.log("Hi, I am " + this.#name + "!");
  }
}
class Student extends Person {
  #sid; // 子类中增加的私有字段#sid
  #major; // 子类中增加的私有字段#major
constructor(name, sid, major) {
	super(name); // 调用父类构造器,初始化姓名
	this.#sid = sid;
	this.#major = major;
}
  get sid() { return this.#sid; }
  set sid(sid) { this.#sid = sid; }
  get major() { return this.#major; }
  set major(major) { this.#major = major; }
  sayHello() { // 覆盖父类中的方法(类比java的重写方法)
	super.sayHello(); // 通过super调用父类的方法
	console.log("I'm from " + this.#major + ".");
}
}
let p = new Person('Alice');
p.sayHello(); // 输出Hi, I am Alice!
let s = new Student('Bob', '1083710315', 'CS');
console.log(s.name); // 调用继承的name方法,输出Bob
s.sayHello(); // 输出 Hi, I am Bob!I’m from CS

模块

一个jS文件就是一个模块
  • 使用export导出,import导入
export let userid ='admin';
export let password ='123456';//./common/profile.js
import {userid, password} from './common/profile.js';
if(userid ==='admin' && password ==='123456') {
  console.log('Welcome!');
}
else {
  console.log('Access is denied!');
}//./index.js
  • node.js使用import需定义package.json
{
  "type": "module"
}//./package.json
一次导出多个变量
  • 导入时可以重名
let userid ='admin';
let password ='123456';
export { userid, password };//./common/profile.js
import {userid as uid, password as pwd} from './common/profile.js';
if(uid ==='admin' && pwd ==='123456') {
  console.log('Welcome!');
}
else {
  console.log('Access is denied!');
}
导入整个模块
  • 使用星号
  • 将模块重命名
let userid ='admin';
let password ='123456';
export { userid, password };//./common/profile.js
import * as user from './common/profile.js';
if(user.userid ==='admin' && user.password ===
'123456') {
  console.log('Welcome!');
}
else {
  console.log('Access is denied!');
}
函数导出与导入
function add(a, b) {
  return a + b;
}
function sub(a, b) {
  return a - b;
}
export { add, sub };
import {add, sub} from './common/math.js';
let x = 5;
let y = 8;
console.log(add(x, y)); // 输出13
console.log(sub(x, y)); // 输出-3
对象导出与导入
export let user = {
  "data": {
	"userid": "admin",
	"password": "123456"
  }
}
import {user} from './common/profile.js';
console.log(user.data.userid); // 输出admin
console.log(user.data.password); // 输出123456
类导出与导入
export class Student {
  constructor(sid, sname, brithyear) {
	this.sid = sid;
	this.sname = sname;
	this.brithyear = brithyear;
  }
  getAge() {
    let date = new Date();
    return date.getFullYear() - this.brithyear;
  }
}
import {Student} from './common/hit.js';
let alice = new Student('1083710314','Alice', 1990);
Student.prototype.sayHello = function() {
  console.log("Hi, I am " + this.sname + ".");
}
console.log(alice.getAge()); // 输出年龄
alice.sayHello(); // 输出Hi, I am Alice.
默认导出

文件

同步获得文件信息
  • statSync
let fs = require("fs");
let stats = fs.statSync('./source.txt');
console.log(stats.size);
异步获得文件信息
  • stat
fs = require("fs");
fs.stat('./source.txt', function(err, stats) {
  if(err) {
	console.log('获取文件信息失败!');
	return;
  }
  console.log(stats.size);
});
同步读写文件
  • readFileSync
  • writeFileSync
  • appendFileSync
import fs from 'fs';
let data = fs.readFileSync('./source.txt');
fs.writeFileSync('./target.txt', data);
console.log('Copy done.');
异步读写文件
  • readSync
  • writeSync
  • appendSync
import fs from 'fs';
fs.readFile('./source.txt', function(err, data) {
  fs.writeFile('./target.txt', data, function(err) {
	if(err) {
	  console.log(err.message);
  	  return;
	}
	console.log('Copy done!');//这里才是拷贝完成
  });
});
同步分段读写
  • openSync
  • readSync
  • writeSync
  • closeSync
异步分段读写
  • open
  • read
  • write
  • close
let fs = require("fs");
let buf = new Buffer.alloc(10);
let fds = fs.openSync('./source.txt','r');
let fdt = fs.openSync('./target.txt','w');//打开目标文件
let len = fs.readSync(fds, buf, 0, buf.length, null);//实际读到的
while(len > 0) {
  fs.writeSync(fdt, buf, 0, len, null);
  len = fs.readSync(fds, buf, 0, buf.length, null);
}
fs.closeSync(fds);//用完关闭
fs.closeSync(fdt);

异步操作

基于回调的异步操作
  • 为了解决读文件和主线程并行的问题
同步和异步
  • 同步指按顺序执行
  • 异步不按顺序执行

Promise

Promise对象三种状态
  • pending(未决断)
  • fulfilled(已决断)
  • rejected(已决断)

在这里插入图片描述

Promise创建和使用
  • Promise创建后立即执行
  • Promise构造器接受一个回调
console.log("Begin");
let promise = new Promise((resolve, reject) => {
setTimeout(
() => {
resolve('Success');
},
2000
);
});
promise.then((data) => {
console.log(data);
}).catch((err) => {
console.log(err)
}).finally(() => {
console.log("Finally");
});
console.log("End");
  • Promise作为函数返回值
import fs from 'fs';
function read(filePath) {
let promise = new Promise((resolve, reject) => {
fs.readFile(filePath, (err, data) => {
if(err)
reject(err);
resolve(data);
});
});
return promise;
}
read('./source.txt')
.then((data) => {
console.log(data.toString());
})
.catch((err) => {
console.log(err);
});
  • all方法
  • race方法
  • 17
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值