es6 some functions about arrays

On the functions of arrays

map

  1. There are three parameters (val, index, all) in the callback function of the map traversal method, which respectively represent the value, subscript and the array being looped.
let arr = [{title:'new1',read:200,hot:true},
        {title:'new2',read:300,hot:true},
        {title:'new3',read:400,hot:true}];
let newarr = arr.map((val, index, all) => {
    return {
        t:`^_^${val.title}`,
        r:val.read+50,
        h:val.hot==true && 'yeah!'
    }
});
console.log(newarr)
  1. filter filtering method
let arr = [{title: 'new1', read: 200, hot: true},
    {title: 'new2',read: 300,hot: false},
    {title: 'new2',read: 300,hot: false},
    {title: 'new3',read: 400,hot: true}];
let newarr = arr.filter((val, index, a) =>{
    return val.hot //In the expression, the returned result istrueStay here
});
console.log(newarr)
  1. forEach traversal has no return value, map has
newarr.forEach((val, index, a) => {
    document.write(`${val.title}--${val.read}--${val.hot}<br>`);
});
  1. some is similar to finding. It returns true if there is a certain condition
let arr = ['apple', 'banana', 'pear'];
let b = arr.some((val, index, a) =>{
    return 'apple';
})
console.log(b)  // The result istrue
  1. Every checks whether every value in the array is qualified
let arr2 = [1, 3, 5, 7, 9];
let c = arr2.every((val, index, a) => {
    return val%2==1;
})
console.log(c) // The result istrue
  1. reduce is used when there is a certain relationship between the items before and after the array
//Summation
let a = arr.reduce((prev, cur, index, arr) => {
    return prev+cur;
})

//Finding factorial
let b= arr.reduce((prev, cur ,index ,arr) =>{
    return prev*cur;
})
  1. Reducereight same as above, opposite direction
let arr = [2, 2, 3];
let e = arr.reduceRight((prev, cur, index, arr) =>{
    return prev ** cur;
})
e // 81
  1. find finds the first qualified value. If it is not found, it is undefined
let arr = [2, 5, 40, 19, 7];
let res = arr.find((val, index, arr) =>{
    return val > 15;//40Come out first, so the result is40
});
console.log(res);// 40
  1. Array.findIndex() is the same as above. It is index
let arr = [2, 5, 40, 19, 7];
let res = arr.findIndex((val, index, arr) =>{
    return val > 15;//40Come out first.40Of index by 2
});
console.log(res); // 2

10.arr.includes() check whether it contains

let arr = [1,5,3,6,8];
let c = arr.includes(3);
console.log(c);
  1. from generates an array, which can be used to convert a class array to an array
function show(){
    let arr = [...arguments];
    let arr = Array.from(arguments);
    //After copying the array, you can perform the array operation
    let last = arr.pop();
    arr.unshift(last);
    console.log(arr);
}
show(1,2,3,4,5)

Posted by mkoga on Sun, 05 Jan 2020 06:19:22 -0800