What is new in es6 compared to es5?

青灯夜游
Release: 2022-10-21 19:08:10
Original
2259 people have browsed it

New content: 1. Let and const keywords are used to declare variables, support block-level scope, and have temporary dead zones; 2. Destructuring assignment is pattern matching for arrays or objects, and then The meaning of assigning values ​​to the variables; 3. The expansion operator can be used to expand the elements in sets and arrays into single elements; 4. Set object, a new data structure, similar to an array, but the members The values ​​are all unique and there are no duplicate values; 5. The constructor methods Array.from() and Array.of().

What is new in es6 compared to es5?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

New features of ES6 than ES5

let, const:

let and const Supports block-level scope and has temporary dead zone (must be declared first and then used, variable promotion is not supported);

const is a constant and must be assigned a value when declared. When the value is assigned to a basic type, it cannot be changed. The value; when the assignment is a reference type, its reference cannot be changed, but operations on the reference type can be performed, such as push of the array, addition, deletion and modification of the properties of the object

Destructuring assignment:

es6 allows extracting values ​​from arrays or objects and assigning values ​​to variables according to a certain pattern, which is called destructuring assignment.

Destructuring assignment is simple and easy to understand in code writing, with clear semantics, making it convenient to obtain data fields in complex objects.

Object destructuring assignment:

let obj = {
  a: 1,
  b: 2
};
let {a, b, c} = obj; // 大括号中的变量名必须和obj的属性名一致
console.log(a, b, c);

// 输出:
// a: 1
// b: 2
// c: undefined
Copy after login

Array destructuring assignment: (same as string)

let arr = ['a', 'b', 'c'];
let [e, f] = arr;	// 中括号中的变量按数组中元素的顺序被赋值
console.log(e, f);

// 输出:
// e: 'a'
// f: 'b'

// 快速交换两个变量值
let a = 1, b = 2;
[a, b] = [b, a];
Copy after login

Expand operator:

Represented by three dots (...), the JavaScript spread operator was introduced in ES6. It can be used to expand elements in collections and arrays into single individual elements.

The spread operator can be used to create and clone arrays and objects, pass arrays as function arguments, remove duplicates from arrays, and more.

The spread operator can only be used on iterable objects. It must be used before the iterable object without any separation. For example:

console.log(...arr);
Copy after login

Array:

let arr1 = [1, 2, 3, 4];
let arr2 = ['a', 'b', ...arr1, 'c'];
console.log(arr2);

// 输出:
// ['a', 'b', 1, 2, 3, 4, 'c']
Copy after login

Object:

let obj1 = {
  a: 1,
  b: 2
};
let obj2 = {
  ...obj1,
  c: 3,
  d: 4
};
console.log(obj2);

// 输出:
// {a: 1, b: 2, c: 3, d: 4}
Copy after login

Remaining parameter processing:

Array:

let arr = [1, 2, 3, 4, 5];
let [a, b, ...c] = arr;	// 将arr后面所有的剩余参数放入c中
console.log(a, b, c);

// 输出:
// a: 1
// b: 2
// c: [3, 4, 5]
Copy after login

Object:

let obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};
let {a, b, ...c} = obj;
console.log(a, b, c);

// 输出:
// a: 1
// b: 2
// c: {c: 3, d: 4}

// 对象的复制(不是传地址)
let obj2 = {...obj};
Copy after login

Set object:

Set is a function provided by ES6 A new data structure, similar to an array, but the values ​​of the members are unique and there are no duplicate values.

  • Set itself is a constructor used to generate Set data structure.

  • Set objects allow you to store unique values ​​of any type, whether primitive values ​​or object references.

  • The elements in Set will only appear once, that is, the elements in Set are unique.

  • In addition, both NaN and undefined can be stored in Set, and NaN are treated as the same value (although NaN !== NaN).

  • The Set function can accept an array (or other data structure with iterable interface) as a parameter for initialization.

Array deduplication:

let arr = [2, 1, 2, 1, 3, 4, 4, 5];
let s = new Set(arr);
arr = [...s];
// arr: [2, 1, 3, 4, 5]
Copy after login

Set method:

let s = new Set([1, 1, 2, 3, 'a']);
// 得到Set元素个数:
s.size;
// 清空集合
s.clear();
// 删除集合中的某个值,返回操作是否成功
s.delete('a');
// 查看集合是否包含某个值
s.has('a');
// 添加一项,返回集合本身的引用
s.add('b');
Copy after login

Map object:

ES6 provides the Map data structure. It is similar to an object and is also a collection of key-value pairs, but the scope of "key" is not limited to strings. Various types of values ​​(including objects) can be used as keys. In other words, the Object structure provides "string-value" correspondence, and the Map structure provides "value-value" correspondence, which is a more complete implementation of the Hash structure. If you need a "key-value" data structure, Map is more suitable than Object.

Map Features:

  • Map objects save key-value pairs and are able to remember the original insertion order of keys.

  • Any value (object or primitive) can be used as a key or a value.

let arr = [
  ['a', 1],
  ['b', 2],
  ['c', 3]
];
let m = new Map(arr);
// m: {'a' => 1, 'b' => 2, 'c' => 3}
Copy after login

Map method:

// 清空Map
m.clear();
// 删除某一项,返回操作是否成功
m.delete(key);
// 获取某一项的值,返回对应的val
m.get(key);
// 是否包含某一项
m.has(key);
// 添加一项,返回Map本身的引用
m.set(key, val);
Copy after login

New function content:

  • Arrow function: No this and arguments

  • Parameter default value

New methods for arrays:

Constructor methods:

  • Convert a class array into Real array: Array.from(arrLike [, mapFunc, mapThis]);

    Parameters:

    • arrLike:Class array
    • mapFunc:The operation function for each item of the class array
    • mapThis:Replace the this of mapFunc Point to

    Another method: let arr = [...arrLike];

  • Convert the parameter list For an array:

    Array.of(...items);

  • 检测一个对象是否是一个数组:

    Array.isArray(obj);

对象的方法:

  • arr.find(callback [, thisArg]):查找数组中满足条件的第一个元素的值

    let arr = [1, 2, 3, 4];
    let val = arr.find((item, index) => item >= 3);
    // val: 3
    let val = arr.find((item, index) => item >= 5);
    // val: undefined
    Copy after login
  • arr.findIndex(callback [, thisArg]):查找数组中满足条件的第一个元素的索引

  • 数组扁平化:

    • arr.flat([depth])

      参数:depth:指定要提取嵌套数组的结构深度,默认为1,当depth = infinity时,无论数组多少层,都提取为一维数组。

    • arr.flatMap(callback[, thisArg])

      参数:callback:对原数组的每个元素进行操作,返回新数组的元素;

      该函数值支持深度为1的扁平化

  • 数组元素填充:arr.fill(value[, start[, end]]);

    用一个固定的值填充一个数组中从起始索引到终止索引内到全部元素。不包括终止索引;不会改变数组长度

    参数:

    • value:用来填充数组元素的值;
    • start:起始索引,默认值为0;
    • end:终止索引,默认值为 arr.length ;
  • arr.includes(valueToFind[, fromIndex]):判断数组中是否包含一个指定的值

    参数:

    • valueToFind:需要查找的值
    • fromIndex:从 fromIndex 处开始向后查找

字符串新增方法:

  • str.startsWith(searchString[, position]):判断当前字符串是否以另一个给定的子字符串开头

    参数:

    • searchString:要搜索的字符串
    • position:在 str 中搜索 searchString 的开始位置,默认为0,也就是真正的字符串开头处
  • str.endsWith(searchString[, position]):判断当前字符串是否以另一个给定的子字符串结束

    参数:

    • searchString:要搜索的字符串
    • position:在str中反向搜索的开始位置,默认为 str.length
  • str.repeat(times):返回重复str字符串times次的字符串

模版字符串:

反引号:``,可以换行

插值表达式:${}

对象新增方法:

  • 简洁表示法:

    let a = 1, b = 2;
    // 原来的表示方法:
    let obj = {
      a: a,
      b: b,
      c: function() {}
    };
    // 简洁表示法:
    let obj = {
      a,
      b,
      c() {}
    };
    Copy after login
  • 属性名表达式:

    let name = "小明";
    let obj = {
      [name]: 111
    };
    console.log(obj);
    // 输出:
    // obj: {'小明': 111}
    
    // 等价于:
    let obj = {};
    obj[name] = 111;
    Copy after login
  • Object.assign(obj1, obj2, ...):将第二个参数即之后的参数对象合并到第一个参数对象中

    let obj1 = {a: 1, b: 2};
    let obj2 = {c: 3, d: 4};
    Object.assign(obj2, obj1);
    // 等价于
    obj2 = {
      ...obj1,
      ...obj2
    }
    // 等价于
    obj2 = Object.assign({}, obj1, obj2);
    Copy after login
  • Object.is(value1, value2):判断两个值是否相等(强类型)

    ===的区别:

    +0 === -0;	// true
    Object.is(+0, -0);	// false
    
    NaN === NaN; // false
    Object.is(NaN, NaN); // true
    Copy after login

    babel编译器:

    将es6语法编译为es5语法

    【相关推荐:javascript视频教程编程视频

    The above is the detailed content of What is new in es6 compared to es5?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!