ES6(2022.11.7-2022.11.11)

目录

let 与 const

一、let 命令

1.基本用法

2.块级作用域

3.与 var 的区别

二、 const 命令

let 与 const 题目

---------------------------------------------------------------------------

属性的遍历(解构赋值)

单层对象

深层对象

数组

乱序解构

---------------------------------------------------------------------------

Promise 容器

promise 状态(promise 承诺 不可以改变)

then/catch

all / race

---------------------------------------------------------------------------

async异步函数

---------------------------------------------------------------------------

for each 用法

一、基本用法

二、循环中断

练习

--------------------------------------------------------------------------------------

for in

for of

--------------------------------------------------------------------------------------

Object.values

--------------------------------------------------------------------------------------

求幂运算符 (**)

--------------------------------------------------------------------------------------

includes 方法

--------------------------------------------------------------------------------------

对象属性和属性值同名省略

--------------------------------------------------------------------------------------

Set 

set创建方式,添加元素

查询有没有相关数字

输出数组的长度

删除某一个元素

set 转换成数组(运用拓展运算符)

set 去除重复性(利用set 不重复性)

--------------------------------------------------------------------------------------

Map

Map的创建,key可以是任何类型

查询有没有相关字段

获取map 的 value

Map 的删除

--------------------------------------------------------------------------------------

模板字符串

--------------------------------------------------------------------------------------

函数剩余参数(arguments 可以输出函数接受的所有实参,是一个类数组)

以前,接受参数输出参数很复杂

ES6接受参数可以用arguments,输出成一个类数组

类数组转换为数组

函数剩余参数,直接输出数组

假设确定第一个传参是1 但是不确定后面需要传的参数,单独获取第一个参数,后面的参数用剩余参数去获取

--------------------------------------------------------------------------------------

数组剩余参数

--------------------------------------------------------------------------------------

对象剩余参数

--------------------------------------------------------------------------------------

拓展运算符

拼接数组

代替Object.assign

--------------------------------------------------------------------------------------

默认参数

函数默认参数

ES6默认参数

--------------------------------------------------------------------------------------

可选链 ?.

--------------------------------------------------------------------------------------

空位合并运算符 ??

--------------------------------------------------------------------------------------

findIndex

--------------------------------------------------------------------------------------

find

--------------------------------------------------------------------------------------

forEach

--------------------------------------------------------------------------------------

map

--------------------------------------------------------------------------------------

filter

--------------------------------------------------------------------------------------

some

every


let 与 const

一、let 命令

1.基本用法

let 和 var 都是用来声明变量,但是 let 命令只在所在的代码块里有效

{
    var a = 10
    let b = 5
    
    console.log(a);//10
    console.log(b);//5
}
    console.log(a);//10
    console.log(b);//undefined

2.块级作用域

ES5 只有 全局作用域 和 函数作用域,没有 块级作用域

会 内层变量可能会覆盖外层变量

计数的循环变量泄露为全局变量

ES6 标准中,由一对大括号包裹形成的作用域就是块级作用域

function f1() {
  let n = 5;
  if (true) {
    let n = 10;
  }
  console.log(n); // 5
}
表示外层代码不受内层代码块的影响,如果 使用的 var ,最后输出的值是 10
function f1() {
  let n = 5;
  if (true) {
    var n = 10;
  }
  console.log(n); // 10
}

3.与 var 的区别

不允许在相同作用域内重复声明

let 不允许在相同作用域内,重复声明同一个变量

//报错
function func() {
  let a = 10;
  var a = 1;
}
//报错
function func() {
  let a = 10;
  let a = 1;
}
不能在函数内部重新声明参数

不存在变量提升

var 命令会发生 “变量提升” 现象,即变量可以在声明之前使用,值为 undefined

// var 的情况
console.log(foo); // 输出undefined
var foo = 2;
//脚本开始运行时,foo 就已经存在,只不过是没有值而已

// let 的情况
console.log(bar); // 报错ReferenceError
let bar = 2;
//变量 bar 用 let 声明,就不会发生变量提升,所以 在脚本运行前 bar 是不存在的,所有抛出了一个错误

暂时性死区(tempoal dead zone 简称 TDZ)

只要块级作用域内存在 let 命令,它所声明的变量就 “绑定” 这个区域,不在受外部影响

var tmp = 123;//存在了 全局变量 tmp

if (true) {
  tmp = 'abc'; 
  let tmp;// 在块级作用域内 let 又声明一个局部变量 tmp
}
//导致后者绑定了这个 块级作用域,所以在 let 声明变量前,对 tmp 赋值都会报错

if (true) {
  // TDZ开始
  tmp = 'abc'; // ReferenceError
  console.log(tmp); // ReferenceError
  let tmp; // TDZ结束 在 let 声明变量前都属于 tmp 的 “死区”
  console.log(tmp); // undefined
  tmp = 123;
  console.log(tmp); // 123
}

其他的死区

function bar(x = y, y = 2) {
  return [x, y];
}
bar(); // 报错
//参数x 默认值等于另一个参数 y ,此时y 还没有声明,属于 “死区”

///

function bar(x = 2, y = x) {
  return [x, y];
}
bar(); // [2, 2]

///


// 不报错
var x = x;


// 报错
let x = x;
// ReferenceError: x is not defined

二、 const 命令

  1. 基本用法

const 声明 一个只读的常量,一旦声明,常量的值不能改变

const PI = 3.1415;
console.log(PI); // 3.1415


PI = 3;
// TypeError: Assignment to constant variable.

const 一旦声明变量,就必须立即初始化,不能留到以后赋值,就会报错(只声明不赋值,就会报错)

const foo;
// SyntaxError: Missing initializer in const declaration

const 的作用域与let命令相同:只在声明所在的块级作用域内有效

if (true) {
  const MAX = 5;
  console.log(MAX);// 5
}


Console.log(MAX); // Uncaught ReferenceError: MAX is not defined

const 命令声明的常量也是不提升,同样存在暂时性死区,只能在声明的位置后面使用

if (true) {
  console.log(MAX); // ReferenceError
  const MAX = 5;
}

const 声明的常量,也和 let 一样不可重复声明

// 以下两行都会报错
const message = "Goodbye!";
const age = 30;

const 保证是变量指向的那个内存地址所保存的数据不得改动

const foo = {};//foo储存的是一个地址,这个地址指向一个对象。不可变的只是这个地址,不能把 foo 指向另一个地址,对象本身是可变的,所以可以添加新的属性


// 为 foo 添加一个属性,可以成功
foo.prop = 123;
foo.prop // 123


// 将 foo 指向另一个对象,就会报错
foo = {}; // TypeError: "foo" is read-only

//对象本身是可变的
const a = [];
a.push('Hello'); // 可执行
a.length = 0;    // 可执行
a = ['Dave'];    // 报错

冻结 对象 使用 Object.freeze方法

const foo = Object.freeze({});


// 常规模式时,下面一行不起作用;
// 严格模式时,该行会报错
foo.prop = 123;

除了将对象本身冻结,对象的属性也可以冻结。下面是一个将对象彻底冻结的函数。

var constantize = (obj) => {
  Object.freeze(obj);
  Object.keys(obj).forEach( (key, i) => {
    if ( typeof obj[key] === 'object' ) {
      constantize( obj[key] );
    }
  });
};

let 与 const 题目

题目一

下面不属于关键字let的特点的是:( B )

A.只在 let 命令所在的代码块内有效

B.会产生变量提升现象

C.同一个作用域,不能重复声明同一个变量

D.不能在函数内部重新声明参数

题目二:

关于关键字const,下列说法错误的是:( D

A.用于声明常量,声明后不可修改

B.不会发生变量提升现象

C.不能重复声明同一个变量

D.可以先声明,不赋值。

题目三:

写出下面两段代码运行结果:

for(var i=0; i<3; i++){

console.log(i);

}

console.log(i);

运行结果?

i = 3

for(let j=0; j<3; j++){

console.log(j);

}

console.log(j);

运行结果?

undefined

题目四:

1. {

2. const person = {name:"小明",gender:"男"};

3. person.name = "张三";

4. person.age = "18";

5. person = {name:"小明",gender:"男",age:"18"}

6. }

语句3能否执行

语句4能否执行

语句5能否执行 不能

---------------------------------------------------------------------------

属性的遍历(解构赋值)

单层对象

以前 输出对象 (冗余)

//对象中有 三个属性
const obj = {
    nickname:'大帅哥',
    age:22,
    gender:'男'
    }
//定义三个变量 接受 三个属性
const nickname = obj.nickname
const age = obj.age
const gender = obj.gender
//依次输出 名称 年龄 性别
console.log (nickname,age,gender)

ES6

const obj = {
    nickname:'大帅哥',
    age:22,
    gender:'男'
    }
const{ nickname ,age , gender) = obj
//依次输出 名称 年龄 性别
console.log (nickname, age, gender)//大帅哥 22 男

深层对象

const obj = {
    nickname:'大帅哥',
    age:22,
    gender:'男',
    doing:{
        morning:'play',
        evening:'sleep'
    }
const { nickname:myname ,doing {morining} }= obj
//定义的nickname已经不存在了,被 myname替代了
console.log(myname ,doing)//大帅哥 play

数组

const arr = [1,2,3]
const [a,b,c] = arr
console.log(a, b, c)// 1 2 3

乱序解构

const arr = [1,2,3]
const {1:a,2:b,0:c} = arr
console.log(a, b, c)// 2 3 1

---------------------------------------------------------------------------

Promise 容器

promise 状态(promise 承诺 不可以改变)

三种:pending(等待) fulfilled(成功) rejected(失败)

从等待 变成 成功 或者是 等待 变成 失败(状态改变后,状态不可逆,状态不可以进行第二次改变)

coust p = new Promise ((resolve,reject) = > {
//ressolve(1)    // 1
//reject(1)      //<rejected>1
//throw 1        //<rejected>1
})
cousole.log(p)

then/catch

new Promise ((resolve,reject) =>{
// resolve(100)        // 成功 100 222
// reject(1111)        // 失败 1111 222
// throw 111
}).then (res = >console.log('成功',res)}
.catch(err = >console.log('失败',err)}
.finally(() = > console.log(222)
new Promise ((resolve,reject) =>{
// resolve(100)        // 第二个then 900
// reject(1)        // catch <reject>1
// throw 111
}).then (res = > new Promise((resolve, reject) = > reject(800 + res)
.then(err = >console.log('第二个then',res)}
.catch(err = >console.log('catch',err)}

all / race

all 方法传入数组,返回一个对象

const createPromise = (delay,flag = true) =>{
    return new Promise((resolve, reject) = >{
    setTimeout(() = >{
     flag ? resolve (‘成功${dalay}):rejevt(‘失败${delay})},delay)
     })
}

//all
Promise.all ([createPromise(1000),createPromise(1500),createPromise(2000)
.then(res = > console.log('成功',res))
.then(err = > console.log('失败',err))
// 成功 ['成功1000','成功1500','成功2000']

Promise.all ([createPromise(1000),createPromise(1500false),createPromise(2000)
.then(res = > console.log('成功',res))
.then(err = > console.log('失败',err))
// 失败 失败1500

//race
//输出第一个执行完的(无论成功还是失败)
Promise.race ([createPromise(2000),createPromise(1500),createPromise(1000)
.then(res = > console.log('成功',res))
.then(err = > console.log('失败',err))
// 成功 成功1000 

Promise.race ([createPromise(2000),createPromise(1500),createPromise(1000,false)
.then(res = > console.log('成功',res))
.then(err = > console.log('失败',err))
// 失败 失败1000 

---------------------------------------------------------------------------

async异步函数

保证了用同步的方式 执行异步操作 实现了排队的效果

默认是返回一个 Promise ,Promise 值就是这个函数的return

const requestLogin = (params) = >{
    return new Promise (resolve => {
    resolve(‘${params.username}很帅’)
    })
}
const requestUserInfo = (params) = >{
    return new Promise (resolve => {
    resolve(‘${params},也很高’)
    })
}
const handleLogin = async () = > {
    const res = await requestLogin({
        username:'大帅哥',
        password:'123456'
    })
    const info = await requestUserInfo(res)
    console.log(info)
}
// 大帅哥很帅,也很高

---------------------------------------------------------------------------

for each 用法

一、基本用法

foreach()方法用于遍历数组,调用数组的每个元素,并将元素传递给回调函数进行处理

语法:array.forEach(function(currentValue,index,arr),thisValue)

参数:

function(currentValue,index,arr) 数组中每个元素需要调用的函数,必需

currentValue:当前元素,必需

index:当前元素的索引值,可选

arr:当前元素所属的数组对象,可选

thisValue 传递给函数的值,用作"this"的值,可选

如果这个参数为空,"this"值为"undefined"

在数组的原始长度以外添加元素 (元素否传递给回调函数)

var words = [1, 2, 3, 4];
var sum=0;
words.forEach(function(word) {
    sum+=word;
	if(word == 2){
		words.push(5);
	}	
});
console.log(sum);// 10 
console.log(words);// [1,2,3,4,5]

添加元素以填充数组中缺少的元素(是,如果该索引尚未传递给回调函数)

var words = ["one", ,"three", "four"];
words.forEach(function(word,index) {
    console.log(word);
    if (word === "one") {
        words[index+1] = "two";
    }
});
console.log(words);//['one','two','three','four']

从数组中删除元素(否,除非该元素已传递给回调函数)

var words = ["one", "two", "three", "four"];
words.forEach(function(word) {
    console.log(word);
    if (word === "two") {
        words.pop();
    }
});
console.log(words);//['one','two','three']

二、循环中断

ES6的 forEach 循环只能通过 return 中断档次循环

let data = [1,2,3,4,5,6]
data.forEach((val,index,arr)=>{
    console.log("当前第"+(index+1)+"次循环开始");
    if(val>3){ 
        return ;
    }
    console.log('val', val);
});
// 当前第1次循环开始
// var 1
// 当前第2次循环开始
// var 2 
// 当前第3次循环开始
// var 3 
// 当前第4次循环开始
// 当前第5次循环开始
// 当前第6次循环开始

forEach只能通过抛异常的方式终止循环

let arr = [0, 1, "stop", 3, 4];
try {
    arr.forEach(element => {
        if (element === "stop") {
            throw new Error("forEachBreak");
        }
        console.log(element); // 输出 0 1 后面不输出
    });
} catch (e) {
    console.log(e.message); // forEachBreak
};
// 0
// 1 
// forEachBreak

当遇到需要终止循环的时候,forEach不再合适。

练习

改写用 foreach

var arr = [1,2,3,4];

for(let i=0; i<arr.length; i++){

console.log(arr[i]);}

------------------------------------>

var arr = [1,2,3,4];

arr.forEach(function(item){

console.log(item-1);

});

--------------------------------------------------------------------------------------

for in

// for in
const arr =[3,2,1]
for (let index in arr) {
    console.log(index) // 0 1 2
// index 遍历的是数组的索引值

// 只需要通过索引值的下标就能得到值
    console.log(arr[index]) // 3 2 1
}


//对象
const obj = {
 name:'大帅哥',
 age:22,
 gender:'男'
}
for (let key in obj){
 console.log(key) // name age gender

 console.log(obj[key]) // 大帅哥 22 男
}

for of

// for of 
const arr = [3, 2 ,1]
for (let value of arr) {
    console.log(value) // 3 2 1
}


// 对象
const obj = {
    name:'大帅哥',
    age:18,
    gender:'男'
}
for(let value of obj){
    console.log(value)// obj is not iterable
}

let of 只能遍历出可迭代对象

对象不是可迭代对象

可迭代对象:数组 、set 、map

对象变成可迭代对象可以参考相关视频:es6:如何将一个普通对象转化为可迭代的对象_嘫颜的博客-CSDN博客

--------------------------------------------------------------------------------------

Object.values

使用 Object.values 就能够把一个对象里所有属性的值 变成 数组

const obj = {
    name: '大帅哥',
    age: 22,
    hobby:'篮球'
}
const values = Object.values(obj)
console.log(values)      // ['大帅哥',22,'篮球']
// 使用 Object.values 就能够把一个对象里所有属性的值 变成 数组

--------------------------------------------------------------------------------------

求幂运算符 (**)

// 3 * 3 

const num = 3 * 3
console.log(num) // 9


// 3 * 3 *3 

const num = 3 * 3 *3
console.log(num) // 27


const num = Math.pow(3,3)
console.log(num) // 27

//ES6
const num = 3 ** 3
console.log(num) // 27

--------------------------------------------------------------------------------------

includes 方法

这个方法既可以被字符串使用也可以被数组使用,作用是传入一个元素,并且判断调用者身上有没有这个元素,如果拥有就返回一个ture ,不拥有的话就返回 false

//ES6

//字符串
const str = '大帅哥'

const bol1 = str.includes('大')
const bol2 = str.includes('小')

console.log(bol1)// true
console.log(bol2)// false


//数组
const arr = [1, 2, 3]

const bol1 = arr.includes(3)
const bol2 = arr.includes(6)

console.log(bol1)// true
console.log(bol2)// false



//indexOf 旧语法

//找到匹配的就返回索引值,没有找到就返回 -1

const arr = [1, 2, 3]

const index1 = arr.indexOf(3)
const index2 = arr.indexOf(5)

console.log(index1)// 2
console.log(index2)// -1


indexOf (旧版本)和 includes (新版本)的区别

includes 能检测出数组里面有没有 NaN(Not a Number)

const arr = [1, 2, 3, NaN]

const index = arr.indexOf(NaN)
console.log(index) // -1

const bol = arr.includes(NaN)
console.log(bol) // ture

--------------------------------------------------------------------------------------

对象属性和属性值同名省略

const fn = ( name, age, hobby) => {
    return {
        name:name,
        age:age,
        hobby:hobby
    }
}
console.log(fn{'大帅哥','18','篮球'}) //{name:'大帅哥',age:'18',hobby:'篮球'}

//箭头函数简写
const fn = (name, age, hobby) => ({
      name: name,
      age: age,
      hobby: hobby
})
console.log(fn{'大帅哥','18','篮球'}) //{name:'大帅哥',age:'18',hobby:'篮球'}


//ES6
const fn = (name, age, hobby) => ({
      name,
      age,
      hobby
})
console.log(fn{'大帅哥','18','篮球'}) //{name:'大帅哥',age:'18',hobby:'篮球'}

--------------------------------------------------------------------------------------

Set 

set创建方式,添加元素

const set = new Set()
set.add(1)
set.add(2)
console.log(set)  //Set{ 1, 2 }


const set = new Set([1, 2])
console.log(set)  //Set{ 1, 2 }

set.add(3)
console.log(set)  //Set{ 1, 2, 3 }

查询有没有相关数字

const set = new Set([1, 2])
console.log(set.has(1))  // true 
console.log(set.has(5))  // false

输出数组的长度

const set = new Set([1, 2, 3])
console.log(set.size) //3

删除某一个元素

const set = new Set([1, 2, 3])
set.delete(1)
console.log(set)//Set{1, 2}

set 转换成数组(运用拓展运算符)

const set = new Set([1, 2, 3])
console.log([...set]) // [1, 2, 3]

console.log(Array.from(set)) // [1, 2, 3]

set 去除重复性(利用set 不重复性)

const arr1 = [1, 2, 1, 2, 3]
console.log([...new Set(arr1)]) // [1, 2, 3]

//不会去重{}
const arr2 = [1, {}, {}, 3]
console.log([...new Set(arr2)]) // [1, {}, {}, 3]

//NaN 本身不等于本身,但是Set会把它去重
const arr2 = [1, NaN, NaN, 3]
console.log([...new Set(arr2)]) // [1, NaN, 3]

--------------------------------------------------------------------------------------

Map

Map的创建,key可以是任何类型

const map = new Map()
map.set('帅哥',18)
map.set(true,985)
map.set(185,'帅哥')
console.log(map) //Map{'帅哥' => 12,ture => 985,185 => '帅哥'}

const map = new Map ([['帅哥',18],[true,985],[185,'帅哥']])
console.log(map) //Map{'帅哥' => 12,ture => 985,185 => '帅哥'}

查询有没有相关字段

const map = new Map ([['帅哥',18],[true,985],[185,'帅哥']])

console.log(map.has('帅哥')) // true

console.log(map.has(123)) // false

获取map 的 value

const map = new Map ([['帅哥',18],[true,985],[185,'帅哥']])

console.log(map.get('帅哥')) // 18

console.log(map.get(123)) // undefined

Map 的删除

const map = new Map ([['帅哥',18],[true,985],[185,'帅哥']])

map.delete(true)

console.log(map)// Map {'帅哥' => 18 , 185 =>'帅哥'}

--------------------------------------------------------------------------------------

模板字符串

//拼接字符串

const nickname = '大帅哥'
const age = 22
const gender = '男'

function getHobby(){
    return '篮球'
}
const myself = nickname + '今年' + age + '岁了,他是个' + gender + '人,喜欢' + getHobby()
console.log(myself)
//大帅哥今年22岁了,他是个男人,喜欢篮球


//ES6
const myself = `${nickname}今年${age}岁了,他是个${gender === '男' ? '大帅哥' : '小姐姐'},喜欢${getHobby()}`
console.log(myself)
//大帅哥今年22岁了,他是个大帅哥,喜欢篮球

--------------------------------------------------------------------------------------

函数剩余参数(arguments 可以输出函数接受的所有实参,是一个类数组)

以前,接受参数输出参数很复杂

function fn (num1, num2) {
    console.log(num1, num2) //1 2
}
fn(1, 2)


function fn (num1, num2, num3, num4)) {
    console.log(num1, num2, num3, num4) //1 2 3 4
}
fn(1, 2, 3, 4)

ES6接受参数可以用arguments,输出成一个类数组

//arguments 可以输出函数接受的所有实参,是一个类数组
function fn () {
    console.log(arguments) //[Arguments] {'0': 1, '1': 2, '2': 3, '3': 4}
}
fn(1, 2, 3, 4)


类数组转换为数组

function fn () {
    console.log([...arguments]) // [1, 2, 3, 4]
}
fn(1, 2, 3, 4)

函数剩余参数,直接输出数组

function fn (...args) {
    console.log([args]) // [1, 2, 3, 4]
}
fn(1, 2, 3, 4)

假设确定第一个传参是1 但是不确定后面需要传的参数,单独获取第一个参数,后面的参数用剩余参数去获取

function fn (num, ...args) {
    console.log(num) // 1
    console.log([args]) // [2, 3, 4]
}
fn(1, 2, 3, 4)

function fn (num1, num2, ...args) {
    console.log(num1, num2) // 1, 2
    console.log([args]) // [3, 4]
}
fn(1, 2, 3, 4)

--------------------------------------------------------------------------------------

数组剩余参数

const [a, ...arr] = [1, 2, 3]
    console.log(a) //1
    console.log(arr) //[2, 3] 
}

--------------------------------------------------------------------------------------

对象剩余参数

const {nickname, ...obj} = {nickname: '大帅哥', age:22, gender: '男'}
console.log(nickname) // 大帅哥
console.log(obj) // {age: 22, gender: '男'}

--------------------------------------------------------------------------------------

拓展运算符

深拷贝和浅拷贝的区别:

        浅拷贝主要是对指针的拷贝,拷贝后两个指针指向同一个内存空间

        深拷贝需要不但对指针进行拷贝,并对指针指向的内容进行拷贝,经过深拷贝后的指针是指向两个不同地址的指针。

const arr1 = [1, 2, 3]
const arr2 = [...arr1]
console.log(arr2)         // [1, 2, 3]
console.log(arr2 === arr1)// false

//对象
const obj1 ={name:'大帅哥'} 
const obj2 = {...obj}
console.log(obj2)         //{name:'大帅哥'}
console.log(obj2 === obj1)//false

拼接数组

const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const res1 = arr1.concat(arr2)
console.log(res1)    // [1, 2, 3, 4, 5, 6]
const res2 = [...arr1, ...arr2]
console.log(res2)    // [1, 2, 3, 4, 5, 6]

代替Object.assign

const obj1 = {name: '大帅哥'}
const obj2 = {age: 22}
const res = Object.assign(obj1, obj2)
console.log(res) // {name: '大帅哥', age: 22}

const res = {...obj1, ...obj2}
console.log(res) // {name: '大帅哥', age: 22}

--------------------------------------------------------------------------------------

默认参数

函数默认参数

function showMe1 (name,age){
   console.log(name, age) // undefined undefined
}
showMe()

//不传参默认值
function showMe2 (name,age){
    name = name || '大帅哥'
    age = age || 22
   console.log(name, age) // 大帅哥 22
}
showMe() 

//传参
function showMe2 (name,age){
    name = name || '大帅哥'
    age = age || 22
   console.log(name, age) 
}
showMe('帅哥',22) // 帅哥 22

ES6默认参数

//不传参默认值
function showMe2 (name = '大帅哥' ,age = 22){
   console.log(name, age) // 大帅哥 22
}
showMe() 


//传参
function showMe2 (name = '大帅哥' ,age = 22){
   console.log(name, age) 
}
showMe('帅哥', 20) //帅哥 20

--------------------------------------------------------------------------------------

可选链 ?.

可选链可以用在数组对象函数身上

数组

const list = null
if(list && list.length){

}        //list 不存在 返回 undefined

//等于

if(list?.length){

}        //list 不存在 返回假

const first =list && list[0] //如果list 存在就会 获取list第一项

const first = list?.[0] 如果list 存在就会 获取list第一项,会判断可选链?.前面的list是否存在

对象

const obj ={

    cat:{
        name:'喵喵'
    }
}
const dog = obj && obj.dog && obj.dog.name

const dog = obj?.dog?.name //存在就继续往下找

函数

const fn = null

fn && fn()

fn?.()

--------------------------------------------------------------------------------------

空位合并运算符 ??

//前面为假输出后面
const a = 0 || '大帅哥'         //大帅哥
const b = '' || '大帅哥'        //大帅哥
const c = false || '大帅哥'     //大帅哥
const d = undefined || '大帅哥' //大帅哥
const e = null || '大帅哥'      //大帅哥

//空位合并运算符,只会把undefined 和 null 当成假值
const a = 0 || '大帅哥'         //0
const b = '' || '大帅哥'        //''
const c = false || '大帅哥'     //false
const d = undefined || '大帅哥' //大帅哥
const e = null || '大帅哥'      //大帅哥

--------------------------------------------------------------------------------------

findIndex

//返回索引值
const findArr = [
    {name:'大帅哥', age:20},
    {name:'帅哥', age:19},
    {name:'哥', age:18}
]
// findIndex
const index = findArr.findIndex((item) => {
    return item.name === '大帅哥'
})
console.log(index)    //1

//缩写
const index = findArr.findIndex(item => item.name === '大帅哥')
console.log(index)    //1

//解构赋值
const index = findArr.findIndex(({name}) => name === '大帅哥')
console.log(index)    //1

--------------------------------------------------------------------------------------

find

//返回 这一项
const findArr = [
    {name:'大帅哥', age:20},
    {name:'帅哥', age:19},
    {name:'哥', age:18}
]
const dashuaige = findArr.find(({ name}) => name === '大帅哥')
console.log(dashuaige)     //  {name:'大帅哥', age:20},

--------------------------------------------------------------------------------------

forEach

作用跟for循环差不多

return 和 break 跳不出循环

用 try catch 跳出循环

const arr = [1, 2, 3, 1, 2, 9, 8]
arr.forEach((item, index, arr) =>{
    console.log(item, index, arr)    //[1, 2, 3, 1, 2, 9, 8]
})

--------------------------------------------------------------------------------------

map

修改数组的每一项,返回新数组,并且不影响原数组

const arr = [1, 2, 3, 1, 2, 9, 8]
const newArr = arr.map(item => item *2)
console.log(newArr)     //[2, 4, 6, 2, 4, 18, 16]
console.log(arr)        //[1, 2, 3, 1, 2, 9, 8]

--------------------------------------------------------------------------------------

filter

过滤的意思,将原数组过滤自己想要的元素到新数组里面,并且不会影响新数组

const arr = [1, 2, 3, 1, 2, 9, 8]
const newArr = arr.filter(item => item >=3)
console.log(newArr)     //[3, 9, 8]
console.log(arr)        //[1, 2, 3, 1, 2, 9, 8]

--------------------------------------------------------------------------------------

some

只要数组中一个元素 大于等于自己想要的值就返回 true

const flag = [1, 2, 3, 1, 2, 9, 8]
const newArr = arr.some(item => item >=3)
console.log(flag)     //true
console.log(arr)        //[1, 2, 3, 1, 2, 9, 8]

every

只要数组中所有元素 大于等于自己想要的值才返回 true

const flag = [1, 2, 3, 1, 2, 9, 8]
const newArr = arr.every(item => item >=3)
console.log(flag)     //false
console.log(arr)        //[1, 2, 3, 1, 2, 9, 8]

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值