ES6
Cada vez que el nacimiento de un estándar significa la perfección del lenguaje, la mejora de funciones y hay algunos aspectos insatisfactorios del javascript en sí.
- La función de promoción variable aumenta la imprevisibilidad del tiempo de ejecución del programa
- La gramática es demasiado laxa, para lograr la misma función, diferentes personas pueden escribir diferentes códigos
dejar
La palabra clave declarada por let tiene un alcance a nivel de bloque. El llamado alcance a nivel de bloque es un {}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>let声明的变量具有块级作用域</title>
</head>
<body>
</body>
<script>
if (true) {
let a = 20;
console.log(a); //20
if (true) {
let b = 50;
console.log(b)//50
}
}
console.log(a) //a is not define
</script>
</html>
podemos evitar que las variables de bucle se conviertan en variables globales
Las variables declaradas por let no serán promocionadas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>let声明的变量不会进行变量提升</title>
</head>
<body>
</body>
<script>
console.log(a) // a is not define
let a = 20;
</script>
</html>
Las variables declaradas por dejar tienen las características de zona muerta temporal
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>let声明的变量具有暂存性死区的特性</title>
</head>
<body>
</body>
<script>
let a = 20;
if(true) {
console.log(a)
let a = 30;
}
</script>
</html>
vamos a entrevistar var
El punto clave de esta pregunta: la variable i es global y el valor de salida de la función es i en el alcance global
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>let面试题</title>
</head>
<body>
</body>
<script>
var arr = [];
for(var i = 0;i<2;i++){
arr[i] = function () {
console.log(i)
}
}
arr[0]()//2
arr[1]()//2
</script>
</html>
deja preguntas de la entrevista
Punto clave: cuando se ejecuta la función, la salida es el valor de i en el alcance del bloque generado por el ciclo anterior
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>let面试题</title>
</head>
<body>
</body>
<script>
let arr = [];
for(let i =0;i<2;i++){
arr[i]= function () {
console.log(i)
}
}
arr[0]()//0
arr[1]()//1
</script>
</html>
constante
const se usa para declarar constantes. Las constantes son la cantidad que el valor (dirección de memoria) no puede cambiar
- Las constantes declaradas con const tienen las características de alcance a nivel de bloque
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>const声明的常量具有块级作用域的特性</title>
</head>
<body>
</body>
<script>
if(true){
const a = 10;
if(true) {
const a =20;
console.log(a)//20
}
console.log(a)//10
}
console.log(a)// a is not define
</script>
</html>
La constante declarada por const debe tener un valor inicial
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>const声明的常量必须赋初始值</title>
</head>
<body>
</body>
<script>
const a;
console.log(a)
</script>
</html>
El valor constante (dirección de memoria) declarado por const no se puede cambiar
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>const声明的常量值不能更改</title>
</head>
<body>
</body>
<script>
const arr = [200,300];
arr[0]='hello';
arr[1]='word';
console.log(arr);//['hello','word']
arr = [200,500];
console.log(arr) //TypeError: invalid assignment to const `arr'
</script>
</html>
La diferencia entre var let const
Cesión de desestructuración
ES6 permite extraer valores de matrices y asignarlos a las variables correspondientes en una correspondencia uno a uno. Los objetos también se pueden deconstruir y asignar.
Desestructuración de matrices
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6之数组解构</title>
</head>
<body>
</body>
<script>
let arr = [1, 2, 3];
let [a, b, c, d] = arr;
console.log(a); //1
console.log(b); //2
console.log(c); //3
console.log(d); //undefined
</script>
</html>
Estructura de objeto
La primera forma de escribir la deconstrucción de objetos.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>对象解构</title>
</head>
<body>
</body>
<script>
let obj = {
name: "张三",
sex: "男"
};
let {
name,
sex
} = obj;
console.log(name);
console.log(sex);
</script>
</html>
La segunda forma de escribir la deconstrucción de objetos.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>对象解构中的第二种写法</title>
</head>
<body>
</body>
<script>
let person = {
name: "尧子陌",
sex: '男'
};
let {
name: myname,
sex: mysex
} = person;
console.log(myname);
console.log(mysex);
</script>
</html>
Función de flecha
Nueva forma de definir funciones en ES6
- Si solo hay una línea de código en el cuerpo de la función y el resultado de la ejecución del código es el valor de retorno, se pueden omitir las llaves.
- Si solo hay un parámetro formal, se pueden omitir los paréntesis
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6之箭头函数</title>
</head>
<body>
</body>
<script>
const fn =() =>{
console.log('hello word')
};
fn() //hello word
//如果函数体内只有一句代码,且代码的执行结果为函数的返回值,则可以省略大括号
const sum =(sum1,sum2)=> sum1+sum2
console.log(sum(20,50))
//在箭头函数中,如果形参只有一个,也可以省略小括号
const fn2 = v => v;
console.log(fn2(20))
</script>
</html>
La función de este punto de la flecha
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>箭头函数中的this</title>
</head>
<body>
</body>
<script>
let obj = {
name: "尧子陌"
};
function fn() {
console.log(this);
return () => {
console.log(this)
}
}
const Rt = fn.call(obj);
Rt()
</script>
</html>
Preguntas de la entrevista sobre la función del cabezal de corte
El punto clave de esta pregunta es: el objeto no puede tener un alcance y no tiene su propio este punto, en este momento esto apunta a esto bajo el alcance global.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>箭头函数面试题</title>
</head>
<body>
</body>
<script>
var age = 100;
var obj = {
age: 20,
say: () => {
alert(this.age)
}
}
obj.say()
</script>
</html>
Parámetros restantes
En ES6, los argumentos no se pueden usar, así que use los parámetros restantes en su lugar
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6之剩余参数</title>
</head>
<body>
</body>
<script>
function sum(...args) {
let total = 0;
args.forEach(item => {
console.log(item); //item代表遍历数组的每一项
total += item
});
return total;
}
console.log(sum(20, 20));
console.log(sum(20, 40, 60));
</script>
</html>
Los parámetros restantes se utilizan junto con la asignación de estructura.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>剩余参数和解构赋值配合使用</title>
</head>
<body>
</body>
<script>
let [s1, ...s2] = ['张三', '李四', '王五']
console.log(s1);
console.log(s2);
</script>
</html>
Operador de propagación
El operador de propagación puede convertir una matriz u objeto en una secuencia de parámetros separados por comas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>扩展运算符</title>
</head>
<body>
</body>
<script>
// 扩展运算符可以将数组或对象转换成以逗号分割的参数序列
let ary = [1, 2, 3];
console.log(...ary);
console.log(1, 2, 3);
</script>
</html>
Concatenar matrices con operaciones de expansión
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>扩展运算符用于合并数组</title>
</head>
<body>
</body>
<script>
// 第一种方法:利用扩展运算符可以合并数组
let arr1 = [1, 2, 3];
let arr2 = [5, 6, 7];
let arr3 = [...arr1, ...arr2];
console.log(arr3);
// 第二种方法:利用push方法合并数组
const arr4 = ['a', 'b', 'c'];
const arr5 = ['d', 'e', 'f'];
arr4.push(...arr5);
console.log(arr4);
</script>
</html>
El operador de propagación puede convertir una pseudo-matriz en una matriz real
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>利用扩展运算符将伪数组转换成真正的数组</title>
<style>
ul {
list-style: none;
}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<script>
let lis = document.querySelectorAll('li');
let arrLis = [...lis];
arrLis.push('尧子陌')
console.log(arrLis);
</script>
</html>
Método de matriz ES6
Matriz. De ()
El método Array.from () puede convertir una pseudo-matriz en una matriz real, y también puede usar una función como segundo parámetro
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array.form()</title>
</head>
<body>
</body>
<script>
let arrayLike = {
'0': '张三',
'1': '李四',
'2': '王五',
'length': '3'
}
console.log(arrayLike);
let arr = Array.from(arrayLike);
console.log(arr);
let arrObj = {
'0': '1',
'1': '2',
'length': '2'
}
// Array.from()可以传递第二个参数,第二个参数为函数
let arr2 = Array.from(arrObj, item => item * 2);
console.log(arr2);
</script>
</html>
encontrar()
Se utiliza para encontrar el primer miembro de la matriz calificado, si no se encuentra, devuelve undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>find()方法</title>
</head>
<body>
</body>
<script>
let arr = [{
id: 1,
name: "尧子陌"
}, {
id: 2,
name: "惊鸿"
}]
// index:索引 item:数组成员
let arrFind = arr.find((item, index) => item.id == 2);
console.log(arrFind);
</script>
</html>
findIndex ()
Averigüe la posición del primer miembro de la matriz que cumple la condición, devuelva -1 si no se encuentra
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>findIndex()</title>
</head>
<body>
</body>
<script>
let arr = [5, 10, 15, 20, 25];
let arrFind = arr.findIndex(item => item > 20);
console.log(arrFind);
</script>
</html>
incluye ()
Indica si una matriz contiene un valor específico y el valor devuelto es un valor booleano.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>includes()方法</title>
</head>
<body>
</body>
<script>
let arr = [1, 2, 3, 4]
console.log(arr.includes(1));
</script>
</html>
Método de cadena ES6
Cadena de plantilla
ES6 agrega un nuevo método para definir una cadena, que se define con comillas invertidas
Características de las cadenas de plantillas
- Las cadenas de plantillas pueden analizar variables
- La cadena de plantilla se puede ajustar
- Las cadenas de plantillas pueden llamar a funciones
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模板字符串</title>
</head>
<body>
</body>
<script>
let name = `尧子陌`;
console.log(name);
// 特点一:模板字符串可以解析变量
let str1 = `大家好,我的名字叫做${name}`;
console.log(str1);
// 特点二:模板字符串可以换行
let people = {
name: "尧子陌",
sex: "男",
age: 18
}
let str2 = `<div>
<span>${people.name}</span>
<span>${people.sex}</span>
<span>${people.age}</span>
</div>`
console.log(str2);
//特点三:模板字符串可以调用函数
function star() {
return '我是一颗星星'
}
let str3 = `${star()}`;
console.log(str3);
</script>
</html>
starsWith () y endsWith ()
- starsWith: indica si la cadena de parámetros está al principio de la cadena original y devuelve un valor booleano.
- endsWith: indica si la cadena de parámetros está al final de la cadena original y devuelve un valor booleano
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>starsWith()与endsWith()</title>
</head>
<body>
</body>
<script>
let str = `hello ES6`;
console.log(str.startsWith('h'));
console.log(str.startsWith('hello'));
console.log(str.endsWith('ES6'));
</script>
</html>
repetir()
El método repeat () puede repetir la cadena original n veces y devolver una nueva cadena
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>repeat()</title>
</head>
<body>
</body>
<script>
console.log('hello '.repeat(2));
console.log('2020'.repeat(3));
</script>
</html>
Establecer estructura de datos
ES6 proporciona un nuevo conjunto de estructura de datos, similar a una matriz, pero los valores de sus miembros son únicos
El conjunto en sí mismo es un constructor que se utiliza para generar la estructura de datos.
Deduplicación de la estructura de datos del conjunto
Nota: Utilice la estructura de datos Establecer para lograr la deduplicación de datos
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set()</title>
</head>
<body>
</body>
<script>
let s = new Set();
console.log(s);
console.log(s.size);
let s1 = new Set([2, 5, 10, 15, 20, 15, 30]);
let s2 = [...s1];
console.log(s2);
console.log(s1.size);
</script>
</html>
Método de instancia en Establecer estructura de datos
- agregar (valor): agrega un valor y devuelve la estructura del conjunto en sí
- eliminar (valor): elimina un valor, devuelve un valor booleano, lo que indica si la eliminación es exitosa
- tiene (valor): devuelve un valor booleano que indica si el valor es miembro de la estructura de datos del conjunto
- clear (): borra todos los miembros, sin valor de retorno
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set()中的实例方法</title>
</head>
<body>
</body>
<script>
let arr = new Set();
console.log(arr.add('a').add('b'));
console.log(arr.delete('b'));
console.log(arr.has('a'));
arr.clear();
console.log(arr.size);
</script>
</html>
Atravesar la estructura de datos del conjunto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>遍历Set数据结构</title>
</head>
<body>
</body>
<script>
let s = new Set(['a', 'b', 'c']);
s.forEach(item => console.log(item));
</script>
</html>