ES6 learn new array method

learning target

ES6 new digital methods to help us more easily process the data

  • Array.from
  • Array.of
  • Array.prototype.fill
  • Array.prototype.includes
  • Array.prototype.find

Think

Jquery code snippet, use css method to get all DOM nodes, and set it to red, if you do not use Jquery provided, we must use document.querySelectorAll, then how to traverse the nodes update the color?

$('.danger').css('color','red')

//我们都知道document.querySelectorAll方法返回的是一个NodeList伪数组
let domArr=document.querySelectorAll('.danger') //NodeList[]
复制代码

Array.from build arrays

Case: Write a function to compute the average, this function accepts any number as a parameter, and then returns the average

function svg(){
    const sum = arguments.reduce(function(a,b){
        return a + b
    })
    return sum / arguments.length
}
console.log(svg(1,2,3,4));  //返回错误消息,因为arguments是伪数组
复制代码

The above function is incorrect, an error will be run arguments.reduce不是一个函数, so we need to convert an array of arguments for real.

ES6 before, we will pseudo-array into an array of a common way is to use Array.prototype.slice on the object pseudo-array method will create a simple case of call on an array slice method without any parameters passed a shallow copy of the array, you can also use similar objects in the array.

    Array.prototype.slice.call(arrayLikeObject);
    //或者使用简单的版本
    [].slice.call(arrayLikeObject)
复制代码

So we use this method arguments into real array

function svg(){
    const args = [].slice.call(arguments)
    const sum = args.reduce(function(a,b){
        return a + b
    })
    return sum / args.length
}
console.log(svg(1,2,3,4));    //2.5

复制代码

The ultimate program

/*
    接受一个类似数组的对象,获得真正的数组
    类似数组的对象也就是上面我说的伪数组,是指具有length属性的任何对象
*/
Array.from(arguments)

复制代码

Rewrite the opening case

let domArr=document.querySelectorAll('.danger') //NodeList集合
let nodesArr=Array.from(domArr);
nodesArr.forEach(function(v,i,a){
    //....
})

复制代码

Note: Array.from on any object can have a length property use, even if the object is only the length property

Array.length({length:30})
/*
    上面这段代码和 new Array(30)完全一样,创建了一个新数组,但是我们
    如果仅仅是想创建只有单一值为30的数组呢?
*、
复制代码

Array.of build arrays

Svg averaging above case, if at this time we only give a parameter, then this function should return svg itself, right? After all, that is the average of a number of its own, but the Array constructor has a special behavior, if only one parameter, and is an integer, then he would create a sparse array of length n, where n is the number that is passed as a parameter to avoid this from happening, es6 provides us with a method to create Array.of

let arr1=new Array(2) //创建c长度为2的空数组 [empty × 2]

let arr2=Array.of(2) // 单个值 [2]
复制代码

Continue to think about two questions
1. Why do not we use it to create a direct literal way?
2. We not only want to create a single array 2, sometimes we do need to create an array with two values do?

Array.prototype.fill build arrays

Case: writing a Tic-tac-toe game, you need to initialize a 3 * 3 grid, we expressed through an array, this array is required to initialize the nine spaces

//错误代码
const board=new Array(9).map(function(i){
    return ''
})

/*
    错误思维:初始化九个未定义的值初始化数组,然后利用map转换为空格
    new Array(9)创建数组时
    {
        length:9
    }
    并不是
    {
        lengt:9,
        0:undefined,
        1:undefined,
        2:undefined,
        3:undefined,
        ....
        8:undefined
    }

    数组会从Array.prototype继承一些方法,执行迭代操作时,数组会在内部先检查长度,然后从索引为0开始等于length时结束,查看自身的任何属性


*/
复制代码

The above case length is 9, but not the actual nine values, we call these missing values ​​hole (holes), holes can not call this method map, so this is the reason we can not initialize string of nine spaces to create, ES6 provides us with a fill () method, you can specify a value filled array

const board=new Array(9).fill('*')
console.log(board); //[ '*', '*', '*', '*', '*', '*', '*', '*', '*' ]
复制代码

Thinking distinguish between the two

let arr1=new Array(9).map(function(){
    return ''
})
let arr2=new Array(9).fill(1)
console.log(arr1);  //[ <9 empty items> ]
console.log(arr2);  //[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]

复制代码

Array.prototype.includes search array

  • There is a prototype string includes methods for determining whether a string contains a value
  • Array prototype also includes a method to check whether the array is an index of a value for the checked value
const A='a';
const B='b';
const C='c'
const CARD=[A,B,C]; //卡片
let optionA='a'
let optionB='b' 
let optionC='ccc'
console.log(CARD.includes(optionA))  //true
console.log(CARD.includes(optionB)) //true
console.log(CARD.includes(optionC)) //false
复制代码

We can also use indexOf determine whether a value within the array, but if you forget the actual development results were compared with -1 instead of the true value, often errors occur

/*
给定制的索引在0处就会返回0,也就是falsy值,反之找不到值就返回-1 也就是truthy值

falsy值是判定位false的任何值:false,undefined,null,NaN,0和空字符串

truthy值是判定为true的任何值,包括负数
*/
console.log(CARD.indexOf('a'));  //0
console.log(CARD.indexOf('b'));  //1
console.log(CARD.indexOf('aaa')); //-1
复制代码

Use the search array Array.prototype.find

Contrast Array.prototype.filter method

  • Assuming that 1000 data, if the first match is found it returns this data 1.filter goal is to return all matching records, the first after the search, will continue to check the remaining 2.find as long as the match is found, immediately stop the search array 3 .find another benefit is that it returns the matches, instead of an array of matches, there is no need to match up to, it can be returned directly to find results from the array
let arr=[1,2,3,4,5,6,7,8,9]
let res=arr.find(function(val){
    return val>2
})
console.log(arr);
console.log(res); //返回3 而不是[3,4,5,6,7,8,9]
复制代码

Jquery css method of beginning again

function $(selector){
    let nodes=document.querySelectorAll(selector);
    return {
        css:function(prop,value){
            Array.from(nodes).forEach(function(node){
                node.style[prop]=value;
            })
            return this
        }
    }
} 
复制代码

Guess you like

Origin blog.csdn.net/weixin_34077371/article/details/91378229