ES6 must Know (iii)--expansion of arrays and objects

Source: Internet
Author: User
Tags array length instance method shallow copy

Expansion of arrays

1. Expand the operator (' ... '), which is equivalent to the inverse of the rest parameter, used to convert an array to a comma-separated sequence of arguments;

console.log(...[1, 2, 3])// 1 2 3console.log(1, ...[2, 3, 4], 5)// 1 2 3 4 5

2. If the extension operator is followed by an empty array, no effect is produced;

1]// [1]

3. Application of the common expansion operators:

Merging arraysLet arr1 = [1,2];Let arr2 = [3,4];Let ARR3 = [5,6];Let NEWARR = [... arr1, ... arr2, ... arr3];Equivalent to ES5 [].concat (arr1, ARR2, ARR3)[1,2,3,4,5,6]Combined with deconstruction assignment (for generating arrays)const [Val, ... rest] = [1,2,3, 4, 5];val //1rest //[2, 3, 4, 5]// Convert the string to a true array let str =  ' mine '; [ ... str] //["M", "I", "N", "E"]//can convert an array of classes into a true array let arraylike = {0:  ' Div.class1 ', 1:  ' Div.class2 ', 2: length: 3}console.log ([... arraylike]) //["Div.class1", "Div.class2", "DIV.CLASS3"]        

4. New Array.from method, you can convert an array-like object (Array-like object) and a traversal (iterable) objects into a real array, the method can also accept the second parameter, similar to the array map method, used to process each element , the processed value is placed in the returned array;

let arr = [ 1 , 2 , 3];arr.map( x => x * x);// [ 1 , 4 , 9 ]Array.from(arr, (x) => x * x)// [ 1 , 4 , 9 ]

5. New Array.of method for converting a set of values to an array (this method can basically be used in place of an array () or new array () to avoid overloading caused by different parameters);

//traditional Array array () //[]array (3) //[,,,]array (1, 2, 3) //[1, 2, 3]//array.ofArray.of () //[]array.of (undefined) //[Undefined]array.of (1) //[1]array.of (1,  2) //[1, 2]           

6. Array instance method find () is used to find the first qualified array member, the parameter of the method is a callback function, the callback function can receive three parameters, followed by the current element, the current element index, the array itself; If the lookup succeeds, the first member that meets the criteria is returned, if there are no eligible members , the undefined is returned;

var arr = [1, 2, 4, 5];var r = arr.find(function( element , index , self ){ return element % 2 == 0;})r // 2

7. Array instance method FindIndex (), the parameter of this method is the same as find (), but the method returns the position of the first qualifying array member, or 1 if all the members do not match the criteria;

var arr = [1, 2, 4, 5];var r = arr.find(function( element , index , self ){ return element % 2 == 0;})r // 1

Both Ps:find () and FindIndex () can find Nan, making up for the insufficiency of the IndexOf method of the array.

8. Array instance method includes (), the method returns a Boolean value that indicates whether a number group contains the given value, similar to the includes method of the string, the method receives two parameters, the first argument is the member to find, and the second parameter represents the starting position of the search (if negative, Is the position of the countdown, if it is greater than the array length, it will be reset to start at 0)

[1, 2, 3].includes(2)     true[1, 2, 3].includes(4)     // false[1, 2, 3].includes(3, 3);  // false[1, 2, 3].includes(3, -1); // true

Expansion of the object

1.ES6 allows you to write directly to variables and functions as properties and methods of an object (in an object, when you write a variable directly, the property name is the variable name, and the value of the variable is the value)

//属性简写var foo = ‘bar‘;var obj = {foo};obj // { foo : "bar" }//变量简写var mine = { foo , method(){ //to do }}

2.ES6 allows the literal definition of an object, using an expression as the property name or method name of the object, that is, placing the expression inside square brackets;

let propKey = ‘foo‘;let obj = {  [propKey]: true,  [‘a‘ + ‘bc‘]: 123, [‘s‘ + ‘ay‘](){ console.log(‘hello world‘) }}obj // {"foo":true,"abc":123}obj.say() // ‘hello world‘

3. The new Object.is () method is used to compare whether the two values are strictly equal, and the behavior of the strict comparison operator (= = =) is basically the same, except that one is +0 not equal to 0, and the other is Nan equals itself.

+0 === -0 //trueNaN === NaN // falseObject.is(+0, -0) // falseObject.is(NaN, NaN) // true

4. The new Object.assign method is used for merging objects, copying all the enumerable properties of the source object (sources) to the target object (target), the first parameter being the destination object, and the subsequent parameters being the source object;

var target = { a: 1 };var source1 = { b: 2 };var source2 = { c: 3 };Object.assign(target, source1, source2);target // {a:1, b:2, c:3}

PS: If the target object has a property with the same name as the source object, or if more than one source object has the same name, the following property overrides the previous property.

var target = { a: 1, b: 1 };var source1 = { b: 2, c: 2 };var source2 = { c: 3 };Object.assign(target, source1, source2);target // {a:1, b:2, c:3}

The method can not be used to target object is undefined and null, will error;

The 5.object.assign method implements a shallow copy rather than a deep copy. If the value of a property of a source object is an object, then the target object copy gets a reference to the object, and the modification affects the original object;

var obj1 = {a: {b: 1}};var obj2 = Object.assign({}, obj1);obj1.a.b = 2;obj2.a.b // 2

The 6.object.assign method is commonly used in the following areas

  • Adding properties to an object
    <pre>
    var _this = {};
    Object.assign (_this, {name: ' Mine '});
    _this//{name: ' Mine '}
    </pre>

  • Add a method to an object
    <pre>
    var _this = {};
    Object.assign (_this, {func () {console.log (' Hello World ')}});
    _this.func ()//Hello World
    </pre>

  • Cloning objects
    <pre>
    var _this = {name: ' Mine '};
    Object.assign ({}, _this);
    </pre>

  • Merging multiple objects
    <pre>
    var _this = {};
    var source1 = {name: ' Mine '};
    var source2 = {mail: ' your '};
    Object.assign (_this, Source1, Source2);
    _this//{"Name": "Mine", "Mail": "Your"}
    </pre>

  • Specifying a default value for a property
    <pre>
    var default = {name: ' Mine ', Mail: ' Your '}
    function ProcessContent (options) {
    Options = Object.assign ({}, default, options);
    To do
    }
    </pre>
    The 7.object.setprototypeof method functions the same as _proto_, which is used to set an object's prototype object, returning the Parameter object itself. It is the ES6 formally recommended method for setting up prototype objects.
    <pre>
    Let Proto = {};
    Let obj = {x:10};
    Object.setprototypeof (obj, proto);

    Proto.y = 20;
    Proto.z = 40;

    obj.x//10
    OBJ.Y//20
    OBJ.Z//40
    </pre>

The 8.object.getprototypeof () method, which is matched to the Object.setprototypeof method, is used to read the prototype object of an object.

9.object.keys (), Object.values (), object.entries () except for the first one, the next two are ES6 new methods for traversing objects, returning arrays, A member is an array of keys, values, and key values for all the enumerable properties of the Parameter object itself (without inheritance).

let obj = { a : 1 , b : ‘hello‘ }Object.keys( obj ); // ["a","b"]Object.values( obj ); // [1,"hello"]Object.entries( obj ); // [["a",1],["b","hello"]]




ES6 must Know (iii)--expansion of arrays and objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.