Built in object extensions of ES6: Array extension method, String extension method and Set data structure

Keywords: Javascript

1. Extension method of Array

1.1 extension operator (expansion syntax)

  • The extension operator (...) can convert an array or object into a comma separated sequence of parameters.
// 1. The extension operator (...) can convert an array or object into a comma separated parameter sequence
let ary = ['a', 'b', 'c'];
// ...ary;  // 'a' , 'b', 'c'
console.log(...ary);   // a b c
  • Extension operators can be applied to merge arrays.
// 2. The extension operator should be used to merge arrays
let ary1 = [1, 2, 3];
let ary2 = [4, 5, 6];
// ...ary1  // 1, 2, 3
// ...ary2  // 4, 5, 6
let ary3 = [...ary1, ...ary2];
console.log(ary3);  // [1, 2, 3, 4, 5, 6]

// The second way to merge arrays
ary1.push(...ary2);
console.log(ary1);  // [1, 2, 3, 4, 5, 6]
  • Converts a class array or traversable object to a real array.
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>

// 3. Use the extension operator to convert the pseudo array into a real array
var divs = document.getElementsByTagName('div');
console.log(divs);  // HTMLCollection(6) [div, div, div, div, div, div]
var ary4 = [...divs];
ary4.push('a');
console.log(ary4);  // (7)[div, div, div, div, div, div, "a"]

1.2 constructor method: Array.from()

  • This method can convert a class array or traversable object into a real array.
// Constructor method Array.from()
// 1. Convert class (pseudo) arrays or traversable objects into real arrays
var arrayLike = {
    "0": "Zhang San",
    "1": "Li Si",
    "2": "Wang Wu",
    "length": 3
};
var ary = Array.from(arrayLike);
console.log(ary);   // ["Zhang San", "Li Si", "Wang Wu"]

  • This method can also accept the second parameter, which is similar to the map method of array. It is used to process each element and put the processed value into the returned array.
// 2. The method can also accept the second parameter, which is similar to the map method of array. It is used to process each element and put the processed value into the returned array
var arrayLike2 = {
    "0": "1",
    "1": "2",
    "length": 2
};
var ary2 = Array.from(arrayLike2, item => item * 2);
console.log(ary2);  // [2, 4]

1.3 example method: find()

The find() method returns the value of the first element of the array that passes the test (judgment within the function).

The find() method calls the function once for each element in the array:

  • When the elements in the array return true when testing the condition, find() returns the qualified elements, and the subsequent values will not call the execution function.
  • undefined if there are no qualified elements

Simply put, the find() method is used to find the first qualified array member. If it is not found, it returns undefined.

be careful:

  • find() for an empty array, the function does not execute.
  • find() does not change the original value of the array.

Syntax:

array.find(function(currentValue, index, arr), thisValue)

Of which:

  • currentValue: required. Represents the current element
  • Index: optional. Represents the index of the current element
  • arr: optional. Represents the array object to which the current element belongs
  • thisValue: optional. The value passed to the function is generally "this". If this parameter is empty, "undefined" is passed to the "this" value.
// The find() method is used to find the first qualified array member. If it is not found, it returns undefined
var ary = [{
    id: 1,
    name: 'Zhang San'
}, {
    id: 2,
    name: 'Li Si'
}];
let target = ary.find(item => item.id == 1);
console.log(target);  // {id: 1, name: "Zhang San"}
let target1 = ary.find(item => item.id == 3);
console.log(target1);  // undefined

1.4 instance method: findIndex()

The findIndex() method returns the position of the first element of the array passing in a test condition (function) that meets the condition.

The findIndex() method calls the function once for each element in the array:

  • When the element in the array returns true when testing the condition, findIndex() returns the index position of the qualified element, and the subsequent value will not call the execution function.
  • If there are no qualified elements, - 1 is returned.

In short, findIndex() is used to find the position of the first qualified array member. If it is not found, it returns - 1.

be careful:

  • findIndex() for empty arrays, the function will not execute.
  • findIndex() does not change the original value of the array.

Syntax:

array.findIndex(function(currentValue, index, arr), thisValue)

Of which:

  • currentValue: required. Represents the current element
  • Index: optional. Represents the index of the current element
  • arr: optional. Represents the array object to which the current element belongs
  • thisValue: optional. The value passed to the function is generally "this". If this parameter is empty, "undefined" is passed to the "this" value.
// findIndex() method
// Used to find the position of the first qualified array member. If it is not found, it returns - 1
let ary = [10, 20, 50];
let index = ary.findIndex(item => item > 15);
console.log(index);  // 1

1.5 example method: includes()

Indicates whether an array contains a given value and returns a Boolean value.

// Include() method
// Indicates whether an array contains a given value and returns a Boolean value
let ary = ['a', 'b', 'c'];
console.log(ary.includes('a')); // true
console.log(ary.includes('e')); // false 
console.log(ary.includes('d')); // false

2. Extension method of String

2.1 template string

The new method of creating strings in ES6 is defined by backquotes.

  • Variables can be parsed in the template string.
// Template string: the new method of creating strings in ES6, which is defined by backquotes (` `)
let name = `Zhang San`;
// 1. Variables can be parsed in the template string
let sayHello = `Hello, My name is ${name}`;
console.log(sayHello);   // Hello, my name is Zhang San

  • You can wrap a line in the template string
// 2. The template string can be wrapped
let result = {
    name: 'zhangsan',
    age: 20
};
let html = `<div>
				<span>${result.name}</span>
				<span>${result.age}</span>
		    </div>`;
console.log(html);
// The output result is:
// <div>
//      <span>zhangsan</span>
//      <span>20</span>
// </div>

  • Functions can be called in the template string.
// 3. Functions can be called in the template string
const fn = () => {
    return 'I am fn function';
};
let html1 = `I am a template string ${fn()}`;
console.log(html1);  // I am the template string and I am the fn function

2.2 instance methods: startsWith() and endsWith()

  • startsWith(): indicates whether the parameter string is at the head of the original string and returns a Boolean value.
  • endsWith(): indicates whether the parameter string is at the end of the original string and returns a Boolean value.
// startsWith() method and endsWith() method
// startsWith(): indicates whether the parameter string is at the head of the original string and returns a Boolean value
// endsWith(): indicates whether the parameter string is at the end of the original string and returns a Boolean value
let str = 'Hello ECMAScript 2015';
let r1 = str.startsWith('Hello');
console.log(r1);  // true
let r2 = str.endsWith('2016');
console.log(r2);  // false

2.3 instance method: repeat()

The repeat method repeats the original string n times and returns a new string.

// repeat() method
// The repeat() method repeats the original string n times and returns a new string
console.log("y".repeat(5));  // yyyyy
console.log('hello'.repeat(2));  // hellohello

3. Set data structure

3.1 Set data structure

ES6 provides a new data structure Set. It is similar to an array, but the values of members are unique and there are no duplicate values.

  • Set itself is a constructor used to generate a set data structure.
// 1. Set itself is a constructor used to generate set data structure.
const s1 = new Set();
console.log(s1.size);  // 0

  • The Set function can accept an array as a parameter for initialization.
// 2. The set function can accept an array as a parameter for initialization
const s2 = new Set(['a', 'b']);
console.log(s2.size);  // 2

// The values of Set members are unique, and there are no duplicate values
const s3 = new Set(["a", "a", "b", "b"]);
console.log(s3.size);  // 2
const ary = [...s3];
console.log(ary);  // ["a", "b"]

3.2 example method

  • add(value): adds a value and returns the Set structure itself.
  • delete(value): deletes a value and returns a Boolean value indicating whether the deletion is successful.
  • has(value): returns a Boolean value indicating whether the value is a member of Set.
  • clear(): clear all members without return value.
// 3. Example method:
const s = new Set();
// (1) To add a value to the set structure, use the add method
s.add(1).add(2).add(3);
console.log(s.size);  // 3

// (2) The method used to delete a value from the set structure is delete
const r1 = s.delete(2); // Delete the 2 value in the set structure
console.log(s.size);  // 2
console.log(r1); // true

// (3) Use has to determine whether a value is a member of the set data structure
const r2 = s.has(1) // Indicates whether there is 1 in the set structure. This value returns a Boolean value
console.log(r2);  // true

// (4) Clear the values in the set data structure using the clear method
s.clear(); // Clear all values in the set structure
console.log(s.size);  // 0
  • Like an array, an instance of a Set structure also has a forEach method to perform certain operations on each member without returning a value
// 4. Like the array, the instance of the set structure also has a forEach method, which is used to perform some operation on each member without return value
// Traverse the set data structure to get values from it
const s5 = new Set(['a', 'b', 'c']);
s5.forEach(value => {
    console.log(value);
});

Posted by sebastienp on Sat, 25 Sep 2021 04:56:16 -0700