JavaScript Some tips

A && and || Magical
Sometimes we need to perform another function to true in a function or variable. E.g:

const task1 = () => {
    console.log('执行 task1');
    return Math.random() >= 0.5;
}

const task2 = () => console.log('task1 执行成功后执行 task2');
if (task1()) task2();

If the above statement can be used directly && abbreviated as:

task1() && task2();

If you also perform task3 task1 after failure (that is, task1 return false), you can use:

const task3 = () => console.log('task1 执行失败后执行 task3');
task1() && task2() || task3();

Default two
ES5 version
when the incoming Y value is 0 or a default value is used when the need for a separate further determination 0

const pow = (x, y) => {
    y = y || 2;
    
    let result = 1;
    for (let i =  0, max = y; i < max; i++) {
        result *= x;
    }

    return result;
}

console.log(pow(2)); // => 4
console.log(pow(2, 3)); // => 8

// 当 y 传值为 0 时, y 取值 2
console.log(pow(2, 0)); // => 4

ES6 version

const pow = (x, y=2) => {
    let result = 1;
    for (let i =  0, max = y; i < max; i++) {
        result *= x;
    }

    return result;
}

console.log(pow(2)); // => 4
console.log(pow(2, 3)) // => 8
console.log(pow(2, 0)); // => 1

Three types of arrays transfer array
array of classes refers to as arguments, jquery objects can use the same access as well as index and length property of an array of like a class of objects but not the array.
No class array slice, map and other aggregate functions, and this is the reason why we sometimes need to convert the array into an array of class.
ES5 conversion method in
the slice method Array prototype is bound to the object call arguments, and is not allowed to pass parameters to return all object elements.

function func() {
    const array = Array.prototype.slice.call(arguments);
    console.log(array.slice(0, 1));
}

func('Google', 'facebook', 'Microsoft'); // => [ 'Google' ]

The conversion method ES6
ES6 the array into an array-based method more.

Extended operator

function func() {
    console.log([...arguments])
}

func('Google', 'facebook', 'Microsoft'); // [ 'Google', 'facebook', 'Microsoft' ]

Use Array.from

function func() {
    console.log(Array.from(arguments))
}

func('Google', 'facebook', 'Microsoft'); // [ 'Google', 'facebook', 'Microsoft' ]

A configuration of four consecutive integer array

// 输出 2 开始连续的8个整数
const array = Array.from({ length: 8}).map((ele, index) => index + 2);
console.log(array); // => [ 2, 3, 4, 5, 6, 7, 8, 9 ] 

// 评论区指出有更简洁的版本, Array.from 自带的映射函数
const array = Array.from({ length: 8}, (ele, index) => index + 2);
console.log(array); // => [ 2, 3, 4, 5, 6, 7, 8, 9 ] 

// 还有一个网友指出可以利用 Array.prototype.keys 来构造
const array = [...Array(8).keys()].map((ele, index) => index + 2)

Five JSON.stringify
depth clones
used to serialize and then deserialize this way to easily clone depth in general, the disadvantage is not clone functions and inherited attributes.
If you also clone function properties, we recommended cloneDeep lodash of.

const me = {
    name: 'lyreal666',
    age: 23,
    speak() {
        console.log(`Hello, I'm ly!`);
    }
}

const clonedMe = JSON.parse(JSON.stringify(me));
console.log(clonedMe); // => { name: 'lyreal666', age: 23 }
console.log(clonedMe.speak === undefined); // => true

Using the second and the third parameter
JSON.stringify second parameter is used to process the attribute values, the third parameter is a character string used to specify the pullback length json output, the digital transmission may be Biography string.

const me = {
    name: 'lyreal666',
    age: 23,
    speak() {
        console.log(`Hello, I'm ly!`);
    }
}

const jsonStr = JSON.stringify(me, (key, value) => key === 'name' ? '老余' : value, 2);

console.log(jsonStr);
/* =>
{
  "name": "老余",
  "age": 23
}
*/

Six elegant traversal of like
using a deconstruction of the assignment and Object.entries.

const me = {
    name: 'lyreal666',
    age: 23,
    speak() {
        console.log(`Hello, I'm ly!`);
    }
}

for (const [key, value] of Object.entries(me)) {
    console.log(`${key}: ${value}`);
}

/* =>
name: lyreal666
age: 23
speak: speak() {
        console.log(`Hello, I'm ly!`);
    }
*/

Seven even by using reduce or even add

const array = [ 1, 2, 3, 4];
// 连加
console.log(array.reduce((p, c) => p + c)); // => 10
// 连乘
console.log(array.reduce((p, c) => p * c)); // => 24

+ Using eight to conversion of other types number

console.log(+'3.14'); // => 3.14
console.log(typeof +'3.14') // => number

Guess you like

Origin blog.csdn.net/weixin_33695082/article/details/90784164
Recommended