返回

Java面试题-前端ES6

发布时间:2023-05-10 05:58:01 174
# json# 数据

ES6

ES6认知

ES6是继ES5之后的一次改进,相对于ES5更加简洁,提高了开发效率

ES6新增的一些特性:

  1. let声明变量和const声明常量,两个都有块级作用域

    ES5中是没有块级作用域的,并且var有变量提升,在let中,使用的变量一定要进行声明

  2. 箭头函数

    ES6中的函数定义不再使用关键字function(),而是利用了()=>来进行定义

  3. 模板字符串

    模板字符串是增强版的字符串,用反引号(`)标识,可以当作普通字符串使用,也可以用来定义多行字符串

  4. 解构赋值

    ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值

  5. for of循环

    for...of循环可以遍历数组、Set和Map结构、某些类似数组的对象、对象,以及字符串

  6. import、export导入导出

    ES6标准中,Js原生支持模块(module)。将JS代码分割成不同功能的小块进行模块化,将不同功能的代码分别写在不同文件中,各模块只需导出公共接口部分,然后通过模块的导入的方式可以在其他地方使用

  7. set数据结构

    Set数据结构,类似数组。所有的数据都是唯一的,没有重复的值。它本身是一个构造函数

  8. ... 展开运算符

    可以将数组或对象里面的值展开;还可以将多个值收集为一个变量

  9. 修饰器 @

    decorator是一个函数,用来修改类甚至于是方法的行为。修饰器本质就是编译时执行的函数

  10. class 类的继承

    ES6中不再像ES5一样使用原型链实现继承,而是引入Class这个概念

  11. async、await

    使用 async/await, 搭配promise,可以通过编写形似同步的代码来处理异步流程, 提高代码的简洁性和可读性

    async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成

  12. promise

    Promise是异步编程的一种解决方案,比传统的解决方案(回调函数和事件)更合理、强大

  13. Proxy代理

    使用代理(Proxy)监听对象的操作,然后可以做一些相应事情

  14. Symbol

    Symbol是一种基本类型。Symbol 通过调用symbol函数产生,它接收一个可选的名字参数,该函数返回的symbol是唯一的

  

Var、Let、Const之间的区别

  • var声明变量可以重复声明,而let不可以重复声明

  • var是不受限于块级的,而let是受限于块级

  • var会与window相映射(会挂一个属性),而let不与window相映射

  • var可以在声明的上面访问变量,而let有暂存死区,在声明的上面访问变量会报错

  • const声明之后必须赋值,否则会报错

  • const定义不可变的量,改变了就会报错

  • const和let一样不会与window相映射、支持块级作用域、在声明的上面访问变量会报错

使用箭头函数应注意什么?

  • 用了箭头函数,this就不是指向window,而是父级(指向是可变的)
  • 不能够使用arguments对象
  • 不能用作构造函数,这就是说不能够使用new命令,否则会抛出一个错误
  • 不可以使用yield命令,因此箭头函数不能用作 Generator 函数

ES6模板字符串的功能

  基本的字符串格式化。将表达式嵌入字符串中进行拼接。用${}来界定

  在ES5时我们通过反斜杠()来做多行字符串或者字符串一行行拼接。ES6反引号(``)就能解决

let name = 'web';
let age = 10;
let str = '你好,${name} 已经 ${age}岁了'
str = str.replace(/\$\{([^}]*)\}/g,function(){
    return eval(arguments[1]);
})
console.log(str);//你好,web 已经 10岁了

介绍下 Set、Map的区别?

应用场景Set用于数据重组,Map用于数据储存

  **Set:** 

  (1)成员不能重复   (2)只有键值没有键名,类似数组   (3)可以遍历,方法有add, delete,has

  Map:

  (1)本质上是健值对的集合,类似集合   (2)可以遍历,可以跟各种数据格式转换

ES6 定义Class

ES6的class可以看作是一个语法糖,它的绝大部分功能ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法

//定义类
class Point { 
  constructor(x,y) { 
      //构造方法
       this.x = x; //this关键字代表实例对象
       this.y = y; 
  } toString() {
       return '(' + this.x + ',' + this.y + ')'; 
  }
}

Promise构造函数?

promise构造函数是同步执行的,then方法是异步执行的

Promise、Async/Await 的区别

  • 事件循环中分为宏任务队列和微任务队列
  • 其中setTimeout的回调函数放到宏任务队列里,等到执行栈清空以后执行
  • promise.then里的回调函数会放到相应宏任务的微任务队列里,等宏任务里面的同步代码执行完再执行
  • async函数表示函数里面可能会有异步方法,await后面跟一个表达式
  • async方法执行时,遇到await会立即执行表达式,然后把表达式后面的代码放到微任务队列里,让出执行栈让同步代码先执行

promise状态,什么时候进入catch?

  • 个状态:pending、fulfilled、reject
  • 两个过程:padding -> fulfilled、padding -> rejected
  • 当pending为rejectd时,会进入catch

下面的输出结果是多少

const promise = new Promise((resolve, reject) => {
    console.log(1);
    resolve();
    console.log(2);
})

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

console.log(4);

1 2 4 3

Promise 新建后立即执行,所以会先输出 1,2,而 Promise.then() 内部的代码在 当次 事件循环的 结尾 立刻执行 ,所以会继续输出4,最后输出3

使用结构赋值

let a = 1;let b = 2;
[a,b] = [b,a];

设计一个对象,键名的类型至少包含一个symbol类型,并且实现遍历所有key

let name = Symbol('name');
 let product = {
    [name]:"洗衣机",    
    "price":799
  };
  Reflect.ownKeys(product);

Set结构,打印出的size值是多少

let s = new Set();
s.add([1]);
s.add([1]);console.log(s.size);

答案:2

两个数组[1]并不是同一个值,它们分别定义的数组,在内存中分别对应着不同的存储地址,因此并不是相同的值

都能存储到Set结构中,所以size为2

如何使用Set去重

let arr = [12,43,23,43,68,12];
let item = [...new Set(arr)];
console.log(item);//[12, 43, 23, 68]

将下面for循环改成for of形式

let arr = [11,22,33,44,55];
let sum = 0;
for(let i=0;i
let arr = [11,22,33,44,55];
let sum = 0;
for(value of arr){
    sum += value;
}

forEach、for in、for of三者区别

  • forEach更多的用来遍历数组
  • for in 一般常用来遍历对象或json
  • for of数组对象都可以遍历,遍历对象需要通过和Object.keys()
  • for in循环出的是key,for of循环出的是value

导入导出模块

// 只导入一个
import {sum} from "./example.js"

// 导入多个
import {sum,multiply,time} from "./exportExample.js"

// 导入一整个模块
import * as example from "./exportExample.js"

导出通过export关键字

//可以将export放在任何变量,函数或类声明的前面
export var firstName = 'Michael';
export var lastName = 'Jackson';
export var year = 1958;

//也可以使用大括号指定所要输出的一组变量
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
export {firstName, lastName, year};

//使用export default时,对应的import语句不需要使用大括号
let bosh = function crs(){}
export default bosh;
import crc from 'crc';

//不使用export default时,对应的import语句需要使用大括号
let bosh = function crs(){}
export bosh;
import {crc} from 'crc';

常用总结

  1. 解构赋值

    let [a, b, c] = [1, 2, 3];
    console.log(a, b, c);
    
    let [json] = [{name: "jack", "age": "18"}];
    console.log(json);
    
    let {name: a, age: b} = {name: "jack", age: "19"};
    console.log(a, b);
    
    let [z, x] = [1, null];
    console.log(z, x == null ? "1" : "2");
    
    // 是否包含
    let name = "pink red blue";
    console.log(name.includes('pink'));
    
    // 开头包含
    let url = "http://wwww";
    console.log(url.startsWith('http://'));
    
    // 结尾包含
    console.log(url.endsWith('http://'));
    
    // 重复次数
    console.log("aaa".repeat(5));
    
    // 向前填充字符串
    console.log("x".padStart(2, 'a'));
    
    // 向后填充字符串
    console.log("c".padEnd(2, "h"));
    
    let arr = ['apple', 'orange', 'banana'];
    console.log(...arr);
    
    // 排序
    function xx(...a) {
    	return a.sort();
    }
    console.log(xx(-1, 7, 5, 2, 0));
    
    let jj = ['a', 'b', 'c'];
    console.log(jj.join(","));
    
    // 字典方法
    let ji = {
        name: "jack", show: () => {
        	return 1;
        }
    };
    console.log(ji.show());
    
  2. 数组循环

    // map循环 ,如果没有返回值,就跟foreach一样;
    let arr = [{name: "jack", age: 18}];
    let newArr = arr.map(((value, index) => {
        let json = {};
        json.n = value.name + "cc";
        json.age = value.age + 6;
        return json;
     }));
     console.log(newArr);
    
    // 过滤
    let list = [{name: "jack", age: 18}, {name: "tom", age: 12}, {name: "ee", age: 20}];
    let newList = list.filter((item, index) => {
        // 只显示年龄大于18岁的数据
        return item.age >= 18;
    });
    console.log(newList);
    
    // some()  某一个包含就返回true
    let arr1 = ['a', 'b', 'c', 'd'];
    let newArr1 = arr1.some(item => {
        return item == 'c';
    });
    console.log(newArr1);
    
    // every()  全部一样返回true
    let arr2 = ['a', 'b', 'c', 'd'];
    let newArr2 = arr2.every(item => {
        return item == 'c';
    });
    console.log(newArr2);
    
    // reduce 求和
    let arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    // 上一个,当前,下标,数组
    let newArr3 = arr3.reduce((previousValue, currentValue, currentIndex, array) => {
        return previousValue + currentValue;
    });
    console.log(newArr3);
    
    // for ... of  多种格式转换
    let arr4 = [{name: "jack", age: 14}, {name: "tom", age: 18}];
    for (let item of arr4) {
        console.log(item.name);
    }
    
    for (let [key, val] of arr4.entries()) {
        console.log('====>', key, val);
    }
    
    for (let val of arr4.values()) {
        console.log('11111=>', val);
    }
    
    let json1 = {name: "jack", age: 20, address: "1111"};
    for (let key in json1) {
        console.log(key + "," + json1[key]);
    }
    
  3. 扩算运算符

    // array.from
    let arr = [1, 2, 3, 4];
    let newArr = Array.from(arr);
    console.log(newArr);
    
    let name = "pink,red,other";
    console.log(Array.from(name));
    
    let json = {
        0: "111",
        1: 18,
        length: 2
    };
    console.log(Array.from(json));
    
    // Array.of
    let other = "pink,red,other";
    console.log(Array.of(other));
    
    // Array.find  查找返回第一个值  ,如果没有,返回 undefined
    let mm = [1, 4, 10, 40, 6];
    let v = mm.find(rep => {
        return rep > 4;
    });
    console.log(v);
    
    // Array.findIndex 找位置,没找到,返回-1
    let mmm = [1, 4, 10, 40, 6];
    let vv = mmm.findIndex(rep => {
        return rep > 4;
    });
    console.log(vv)
    
    // Array.fill  填充   (填充内容,开始位置,结束位置)
    let ter = new Array(5);
    console.log(ter.fill('你好',1,5))
    
  4. 对象

    let name = "jack";
    let age = 19;
    // name:name    等同写法
    let json = {
        name, age, show() {
            return "1"
        }
    };
    console.log(json.show());
    
    // 判断两个是否相等
    console.log(Object.is('111', '222'));
    console.log(Object.is(({name: "jack"}).toString(), ({name: "jack"}).toString()));
    console.log(Object.is(1, 1));
    
    // 合并  assign()
    let json1 = {name: "jack"};
    let json2 = {age: 19};
    let json3 = Object.assign(json1, json2);
    console.log(json3);
    
    // 后者覆盖前者
    let name11 = ['name'];
    let age11 = ['1111'];
    console.log(Object.assign(name11, age11));
    
    // 简写
    let {keys, values, entries} = Object;
    let jsonss = {a: "1", b: "2", c: "3"};
    for (let k of keys(jsonss)) {
        console.log(k);
    }
    for (let v of values(jsonss)) {
        console.log(v);
    }
    for (let other of entries(jsonss)) {
        console.log(other);
    }
    for (let [k, v] of entries(jsonss)) {
        console.log(k, v);
    }
    
  5. 模块化

    // es1.js ===============================================
    // 常量
    const a = 1;
    const b = 2;
    
    // 函数方法
    let show = () => {
        return "show======》";
    };
    
    // 求和
    const sum = () => {
        return a + b;
    };
    
    export {
        a, b, sum, show
    }
    
    class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
    
        showName() {
            return `我的名字是${this.name}`;
        }
    }
    
    export default {Person};
    
    import Person, {show, sum, a, b} from '<%=request.getContextPath()%>/js/module/es1.js'
    
    let ttt = new Person.Person('张');
    console.log(ttt.showName());
    console.log(show());
    console.log(sum());
    console.log(a, b);
    
    // es2.js ==============================================
    const a = 12;
    const b = 14;
    export {
        a, b
    }
    
    // 动态引入
    import('<%=request.getContextPath()%>/js/module/es2.js').then(rep => {
        console.log(rep.a)
    });
    
  6. 类和继承

    // 原始方法
    function sh(name, age) {
        this.name = name;
        this.age = age;
    }
    
    sh.prototype.show = function () {
        return this.name;
    };
    
    let ter = new sh('张三', 18);
    // console.log(ter.show());
    
    // 新方法
    class Dog {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
    
        show() {
            return `这只狗叫${this.name},今年${this.age}岁了`;
        }
    }
    
    console.log(new Dog('小黑', 5).show());
    
    // generator 函数   解决异步操作
    function* pop() {
        yield "111";
        yield "222";
        yield "333";
        yield showTemp();
        return "gogogo";
    }
    
    function showTemp() {
        console.log('进入方法=====》');
        return "444";
    }
    
    let temp = pop();
    console.log(temp.next());
    console.log(temp.next());
    console.log(temp.next());
    console.log(temp.next());
    console.log(temp.next());
    
  7. 异步

    async function show() {
        /*let name = await "12312";
        return name;*/
        let json = await {name: "jack", age: 19};
        return json;
    }
    
    show().then(rep => {
        console.log(rep);
    });
    
  8. set

    // set
    let arr = new Set(['1', '2', '2']);
    arr.add("4");
    arr.delete("4");
    for (let [k, v] of arr.entries()) {
        console.log(k, v)
    }
    
    // foreach
    arr.forEach((v, k) => {
        console.log(k, v)
    });
    
    let pop = [1, 2, 3, 5, 2, 4, 5, 6, 7, 8, 5, 4, 3, 1, 2, 7];
    let newArr = [...new Set(pop)];
    console.log(newArr.sort());
    
  9. map

    let map = new Map();
    map.set("a", "1");
    map.set("b", "2");
    map.set("c", "3");
    console.log(map);
    map.delete("c");
    console.log(map);
    console.log(map.has("a"));
    console.log(map.get("b"));
    
    for (let [k, v] of map) {
        console.log(k, v)
    }
    
  10. 数字(数值变化)

    // 判断是否是NAN
    let aa = 12;
    console.log(isNaN(aa));
    console.log(Number.isNaN(aa));
    
    // 判断是否是数字
    console.log(Number.isFinite(aa));
    
    // 判断数字是否是整数
    console.log(Number.isInteger(12));
    console.log(Number.isInteger(12.5));
    console.log(Number.parseInt(77.2));
    console.log(Number.parseFloat(55.22));
    
    
    // math////////////////////////////////
    console.log(2**4);
    console.log(Number.isSafeInteger(2**53));
    console.log(Number.isSafeInteger(Math.pow(2,53)));
    
    // 截断  不管四舍五入
    console.log(Math.trunc(4.55));
    
    // 判断一个数到底是整数,负数,0,   其他值就是NaN
    console.log(Math.sign(30));  // 1
    console.log(Math.sign(-30)); // -1
    
    // 立方根
    console.log(Math.cbrt(27));  // 3
    
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
引导完成第一个 Spring Boot 项目 2023-05-10 03:02:51