ES6 new method

character string

includes()

console.log('abc'.includes('a'));//true
console.log('abc'.includes('ab'));//true
console.log('abc'.includes('ac'));//false

The second parameter - start search location, which is 0 by default

console.log('abc'.includes('a', 0));//true
console.log('abc'.includes('a', 1));//false

Application - URL add parameters

https://www.imooc.com/
https://coding.imooc.com/?c=javascript&sort=1

let url = 'https://www.imooc.com/';
const addURLParam = (url, name, value) => {
    // Function: if it does not exist? Then splice? If it already exists? Then splice&
    // Ternary operator 
    url += url.includes('?') ? '&' : '?';
    // Function: splicing key value pairs
    // Template string
    url += `${name}=${value}`;
    return url;
};
url = addURLParam(url, 'c', 'javascript');
console.log(url);
url = addURLParam(url, 'sort', '1');
console.log(url);

Padstart() & padend() - fill

console.log('x'.padStart(5, 'ab'));//ababx
console.log('x'.padEnd(5, 'ab'));//xabab

parameter
1) Original string length > = maximum length
The string will not be cut, and the supplement will not take effect

console.log('xxx'.padStart(2, 'ab'));//xxx
 console.log('xxx'.padEnd(2, 'ab'));//xxx

2) Original string length + filled string length > maximum length
Truncate the complement string exceeding the number of bits, and the original string remains unchanged

console.log('abc'.padStart(6, '01234'));//012abc
console.log('abc'.padEnd(6, '01234'));//abc012

3) Omit the second parameter and fill in the blank by default

console.log('abc'.padStart(6));//   abc
console.log('abc'.padEnd(6));//abc

Application - display date format to ensure two digits

console.log('10'.padStart(2, 0));//10
console.log('1'.padStart(2, 0));//01

trim() - clear spaces

Clear space at both ends (trim)
Clear whitespace in header (trimstart)
Clear trailing whitespace trimEnd()
The middle space is not cleared

<input id='username' type="text">
<button id='btn'>Submit</button>
<script>
    const usernameInput = document.getElementById('username');
    const btn = document.getElementById('btn');
    btn
    btn.addEventListener('click', () => {
        // First clear the leading and trailing spaces, and then verify that the content of the input box is not empty
        if (usernameInput.value.trim() !== '') {
            console.log('Can submit');
        } else {
            console.log('Non submittable');
        }
    }, false);
</script>

array

includes()

Following strict equality = = =, in particular, it is considered that NaN is self equal

console.log([1, 2, 3].includes('2'));//false
console.log([1, 2, 3].includes(2));//true
console.log([1, 2, NaN].includes(NaN));//true

The second parameter - start search location, which is 0 by default

console.log([1, 2, 3].includes(2, 2));//false

Application - de duplication

const arr = [];
for (const item of [1, 2, 1]) {
    if (!arr.includes(item))
        arr.push(item);
}
console.log(arr);

Array.from()

Convert to array

console.log(Array.from('str'));//['s', 't', 'r']

Third parameter
The function is similar to the map method of array: process each element, and put the processed value into the returned array

console.log(Array.from('12', value => value * 2));//[2, 4]
console.log(Array.from('12').map(value => value * 2));//[2, 4]
console.log([1, 2].map(value => {
    return value * 2
})
);//[2, 4]

Use occasion

1) Native ergodic
Array, string, class array (arguments, Nodelist), Set, Map, etc

console.log(Array.from(new Set([1, 2, 1])));//[1, 2]
console.log([...new Set([1, 2, 1])]);//[1, 2]

2) Non-native ergodic
Objects with length and index attributes

const obj = {
     '0': 'a',
     '1': 'b',
     name: 'Alex',
     length: 3
 };
 console.log(Array.from(obj));// ['a', 'b', undefined]
 console.log([...obj]);//report errors

find()

Find a return that meets the condition

console.log([1, 5, 10, 15].find((value, index, arr) => {
      console.log(value, index, arr);
      console.log(this);//windows
      return value > 9;//10
  }, document)
);

findIndex()

Find one that meets the criteria and return its index

console.log([1, 5, 10, 15].findIndex((value, index, arr) => {
    console.log(value, index, arr);
    console.log(this);windows
    return value > 9;//2
  }, document)
);

Apply - returns the object that satisfies the property value

const students = [
    {
        name: 'Zhang San',
        sex: 'male'
    }, {
        name: 'Li Si',
        sex: 'female'
    }, {
        name: 'Wang Wu',
        sex: 'male'
    }
];
console.log(students.find(value => value.sex === 'female'));
//{name: 'Li Si', sex: 'female'}
console.log(students.findIndex(value => value.sex === 'female'));
//1

object

Object.assign() - merge objects

Object. Assign (target object, source object 1, source object 2,...)
If the parameter is not an object, it will be converted to an object by default and then merged

const apple = {
     color: 'gules',
     shape: 'spherical',
     taste: 'sweet'
 };
 const pen = {
     color: 'black',
     shape: 'cylindrical',
     use: 'write'
 };

1) After merging into the first parameter (object), the merged object is returned
2) Overwrite the previous attribute after the attribute with the same name

console.log(Object.assign(apple, pen));
//{color: 'Black', shape: 'cylindrical', taste: 'sweet', use: 'write'}
console.log(apple); //ditto
console.log({ ...apple, ...pen });//ditto 
console.log(Object.assign(apple, pen) === apple);//true

3) You can merge multiple objects

  console.log(Object.assign({}, apple, pen));

Apply - merge default and user parameters

const Loguser = userOptions => {
    const DEFAULTS = {
        username: 'ZhangSan',
        age: 0,
        sex: 'male'
    };
    const options = Object.assign({}, DEFAULTS, userOptions);
    console.log(options);
};
Loguser();
//{username: 'ZhangSan', age: 0, sex: 'male'}
Loguser({});//ditto
Loguser({ username: 'Alex' });
//{username: 'Alex', age: 0, sex: 'male'}

Object.keys(),Object.values(),Object.entries()

Is a constructor method that returns an array

const person = {
    username: 'ZhangSan',
    age: 0,
    sex: 'male'
};
console.log(Object.keys(person));//['username', 'age', 'sex']
console.log(Object.values(person));//['ZhangSan', 0, 'male']
console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]

keys(), value(), and entries() of the array are instance methods that return Iterator

console.log([1, 2].keys());//Array Iterator {}
 console.log([1, 2].values());//Array Iterator {}
 console.log([1, 2].entries());//Array Iterator {}

for...of

Same as for... in
There is no guarantee that the order is what we see

const person = {
    username: 'ZhangSan',
    age: 0,
    sex: 'male'
};
for (const key of Object.keys(person)) {
    console.log(key);
}
for (const value of Object.values(person)) {
    console.log(value);
} for (const entrie of Object.entries(person)) {
    console.log(entrie);
}
for (const [key, value] of Object.entries(person)) {
    console.log(key, value);
}    

Keywords: ECMAScript

Added by Blesbok on Mon, 07 Mar 2022 09:49:32 +0200