JavaScript Day18 - 阵列操作(filter、find、findIndex)

filter

  • filter() 会建立一个新的阵列,其内容为原阵列的每一个元素经由回呼函式判断後所回传的结果之集合
    • 可以看到是回传一个新的阵列,所以原本的阵列不会改变
    • 可以搭配箭头函式来使用
    • 需要有回传值 return
  • map() 比,map() 是回传运算结果,阵列大小一样,filter() 回传判断 true 的值,阵列大小可能不同
const arr = [1, 2, 3, 4];

// filter
const filter1 = arr.filter(x => x>2);

// map
const map1 = arr.map(x => x>2);

console.log(filter1); // [3, 4]
console.log(map1); // [false, false, true, true]

参考资料

Array.prototype.filter()
JavaScript 阵列处理方法 [filter(), find(), forEach(), map(), every(), some(), reduce()]
JavaScript Array filter() (筛选阵列元素)

find、findIndex

  • find:回传符合条件的第一个值,若无满足条件则回传 undefined
  • findIndex:回传符合条件的第一个值的顺序,若无满足条件则回传 -1
const arr = [1, 2, 3, 4];

// find
const find1 = arr.find(x => x>2);
const find2 = arr.find(x => x>5);

// findindex
const findindex1 = arr.findIndex(x => x>2);
const findindex2 = arr.findIndex(x => x>5);

console.log(find1); // 3
console.log(find2); // undefined
console.log(findindex1); // 2
console.log(findindex2); // -1

参考资料

Array.prototype.find()
Array.prototype.findIndex()
JavaScript 阵列处理方法 [filter(), find(), forEach(), map(), every(), some(), reduce()]

次回

预计开始说明 AJAX 了


<<:  Day 21:开始来学资料系结:文字插值

>>:  试着掌握潜在客户需求

Day 19 不得不变的学习方式

事情在好起来之前,总会先变很坏,然後才会慢慢的变好。在经历这些过程後,记得要把失去的补回来,把得到的...

LeetCode 双刀流:70. Climbing Stairs

70. Climbing Stairs 这是一个动态规划的经典题目「爬楼梯」,这个题目根据规则利用...

VoK Grid 各种资料型态过滤器 - day15

前情提要 在前面的例子里,我们使用Grid来展示学生资料 grid = grid { isExpan...

[Day 23] 针对API的单元测试(三)

我们今天来针对API做更进一步的测试, 假如我们今天要取得一个使用者资料, 这个使用者的资料有 代号...

Day22:ws 整合 Vue 渲染聊天讯息

前面的 socket.io 使用原生 JS 来写 Demo,这边就试着改用框架来处理,不过毕竟目前还...