ES6学习笔记之数组

  • 使用set对象给数组去重
    [...new Set(array)]

  • 字符串数组转数字数组
    ['1', '2', '3'].map(Number); // [1, 2, 3]

  • 构造数组
    Array(5).fill().map((_,i) => i+1); // [1, 2, 3, 4, 5]

  • 数组求和第一弹

function addUp() {
  let total = 0;
  for(let num of arguments) {
    total += num;
  }
  return total;
}

addUp(1, 2, 3, 4);  // 10
  • 数组求和第二弹
function addUp() {
  const nums = Array.from(arguments);
  return nums.reduce((prev, next) => prev + next, 0)
}

addUp(1, 2, 3, 4);  // 10
  • 类数组转数组
<div class="people">
  <p>Jay</p>
  <p>Eason</p>
  <p>David</p>
</div>
const people  = Array.from(document.querySelectAll('.people p'));
const names = people.map(person => person.textContent);
console.log(names);  // ['Jay', 'Eason', 'David']
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容