Home >Web Front-end >JS Tutorial >Detailed explanation of new feature examples of array extension

Detailed explanation of new feature examples of array extension

零下一度
零下一度Original
2017-06-26 10:12:491143browse

I feel that a lot of practical features have been added to the expansion of arrays, and they feel quite important

1. Array.of() converts data variables into Array form

{
  let arr = Array.of(3,4,7,9,11);
  console.log('arr=',arr);//[3,4,7,9,11]

  let empty=Array.of();//[]
  console.log('empty',empty);
}

  2. Array.from() is used to convert two types of objects into real arrays: Array-like objects (array-like object) and traversable (iterable) objects (including ES6’s new data structures Set and Map)

At the same time Array. from can also accept a second parameter, which is similar to the map method of an array. It is used to process each element and put the processed value into the returned array.

{
  let p=document.querySelectorAll('p');
  let pArr=Array.from(p);
  pArr.forEach(function(item){
    console.log(item.textContent);
  });

  console.log(Array.from([1,3,5],function(item){return item*2}));//[2,6,10]
}

 3. fill(data,startIndex,endIndex-1) fills the array. If there is only one data parameter, all will be replaced. If there are three parameters Replace all startIndex~endIndex-1 with data

{
  console.log('fill-7',[1,'a',undefined].fill(7));//[7,7,7]
  console.log('fill,pos',['a','b','c'].fill(7,1,3));
}

 4. keys (return all array subscripts) values ​​(return all values ​​of the array) entries (Including all keys and values) 

{  for(let index of ['1','c','ks'].keys()){
    console.log('keys',index);
  }  for(let value of ['1','c','ks'].values()){
    console.log('values',value);
  }  for(let [index,value] of ['1','c','ks'].entries()){
    console.log('values',index,value);
  }
}

  5. copyWithin(p1,p2,p3) From The p1 position starts to be overwritten with the data from p2 to p3-1

{
  console.log([1,2,3,4,5].copyWithin(0,3,4));//[4,2,3,4,5]
}

 6. find() stops when it finds the first value that meets the conditions and findIndex() stops when it finds the index of the first qualified value

{
  console.log([1,2,3,4,5,6].find(function(item){return item>3}));//4
  console.log([1,2,3,4,5,6].findIndex(function(item){return item>3}));
}
{
  console.log('number',[1,2,NaN].includes(1));//true
  console.log('number',[1,2,NaN].includes(NaN));//true
}

The above is the detailed content of Detailed explanation of new feature examples of array extension. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn