ES6
표준이 탄생 할 때마다 언어의 완성, 기능 향상, 자바 스크립트 자체의 불만족스러운 측면이 있습니다.
- 변수 승격 기능은 프로그램 런타임의 예측 불가능 성을 증가시킵니다.
- 문법이 너무 느슨하여 동일한 기능을 수행하기에는 다른 사람들이 다른 코드를 작성할 수 있습니다.
허락하다
let에 의해 선언 된 키워드는 블록 수준 범위를 가지며, 이른바 블록 수준 범위는 {}입니다.
<!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>
let은 루프 변수가 전역 변수가되는 것을 방지 할 수 있습니다.
let에 의해 선언 된 변수는 승격되지 않습니다.
<!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>
let에 의해 선언 된 변수는 일시적인 데드 존의 특성을 갖습니다.
<!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>
var 인터뷰하자
이 질문의 요점 : 변수 i는 전역이고 함수의 출력 값은 전역 범위에서 i입니다.
<!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>
인터뷰 질문하자
요점 : 함수가 실행될 때 출력은 이전 루프에서 생성 된 블록 범위의 i 값입니다.
<!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>
const
const는 상수를 선언하는 데 사용됩니다. 상수는 값 (메모리 주소)이 변경할 수없는 양입니다.
- const로 선언 된 상수는 블록 수준 범위의 특성을 갖습니다.
<!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>
const로 선언 된 상수에는 초기 값이 있어야합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>const声明的常量必须赋初始值</title>
</head>
<body>
</body>
<script>
const a;
console.log(a)
</script>
</html>
const로 선언 된 상수 값 (메모리 주소)은 변경할 수 없습니다.
<!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>
var let const의 차이점
구조화 할당
ES6를 사용하면 배열에서 값을 추출하여 일대일 대응으로 해당 변수에 할당 할 수 있습니다. 객체를 분해하고 할당 할 수도 있습니다.
배열 분해
<!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>
개체 구조
객체 분해를 작성하는 첫 번째 방법
<!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>
객체 분해를 작성하는 두 번째 방법
<!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>
화살표 기능
ES6에서 함수를 정의하는 새로운 방법
- 함수 본문에 한 줄의 코드 만 있고 코드 실행 결과가 반환 값이면 중괄호를 생략 할 수 있습니다.
- 형식 매개 변수가 하나만있는 경우 괄호를 생략 할 수 있습니다.
<!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>
화살표 기능의 this 지점
<!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>
커팅 헤드 기능 면접 질문
이 질문의 요점은 객체가 범위를 가질 수없고 자신의이 지점도 가지고 있지 않다는 것입니다.이 시점에서 이것은 전역 범위에서 이것을 가리 킵니다.
<!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>
나머지 매개 변수
ES6에서는 인수를 사용할 수 없으므로 대신 나머지 매개 변수를 사용하십시오.
<!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>
나머지 매개 변수는 구조 할당과 함께 사용됩니다.
<!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>
스프레드 연산자
확산 연산자는 배열 또는 객체를 쉼표로 구분 된 일련의 매개 변수로 변환 할 수 있습니다.
<!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>
확장 작업을 통해 어레이 연결
<!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>
확산 연산자는 의사 배열을 실제 배열로 변환 할 수 있습니다.
<!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>
ES6 어레이 방법
Array.from ()
Array.from () 메서드는 의사 배열을 실제 배열로 변환 할 수 있으며 함수를 두 번째 매개 변수로 사용할 수도 있습니다.
<!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>
찾기()
첫 번째 정규화 된 배열 구성원을 찾는 데 사용됩니다. 찾을 수없는 경우 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 ()
조건을 만족하는 첫 번째 배열 구성원의 위치를 찾고 찾지 못하면 -1을 반환합니다.
<!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>
포함 ()
배열에 특정 값이 포함되어 있고 반환 된 값이 부울 값인지 여부를 나타냅니다.
<!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>
ES6 문자열 방법
템플릿 문자열
ES6는 백틱으로 정의되는 문자열을 정의하는 새로운 방법을 추가합니다.
템플릿 문자열의 특징
- 템플릿 문자열은 변수를 구문 분석 할 수 있습니다.
- 줄 바꿈 할 수있는 템플릿 문자열
- 템플릿 문자열은 함수를 호출 할 수 있습니다.
<!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 () 및 endsWith ()
- starsWith : 매개 변수 문자열이 원래 문자열의 맨 앞에 있는지 여부를 나타내며 부울 값을 반환합니다.
- endsWith : 매개 변수 문자열이 원래 문자열의 끝에 있는지 여부를 나타내고 부울 값을 반환합니다.
<!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>
반복()
repeat () 메서드는 원래 문자열을 n 번 반복하고 새 문자열을 반환 할 수 있습니다.
<!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>
데이터 구조 설정
ES6는 배열과 유사한 새로운 데이터 구조 세트를 제공하지만 멤버 값은 고유합니다.
세트 자체는 데이터 구조를 생성하는 데 사용되는 생성자입니다.
Set 데이터 구조의 중복 제거
참고 : 데이터 중복 제거를 위해 데이터 구조 설정을 사용하십시오.
<!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>
데이터 구조 설정의 인스턴스 방법
- add (value) : 값을 추가하고 Set 구조 자체를 반환합니다.
- delete (value) : 값 삭제, 삭제 성공 여부를 나타내는 부울 값 반환
- has (value) : 값이 Set 데이터 구조의 멤버인지 여부를 나타내는 부울 값을 반환합니다.
- clear () : 모든 멤버 지우기, 반환 값 없음
<!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>
Set 데이터 구조 탐색
<!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>