当前位置:Gxlcms > JavaScript > javascript遍历方法的介绍(代码示例)

javascript遍历方法的介绍(代码示例)

时间:2021-07-01 10:21:17 帮助过:3人阅读

本篇文章给大家带来的内容是关于javascript遍历方法的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

有用到object对象的转换成数组,然后又想到了遍历方法,所以,也想记录下

1. 终止或者跳出循环

  • break跳出循环体,所在循环体已结束

  • continue跳出本次循环,进行下一次循环,所在的循环体未结束

  • return 终止函数执行

  1. for (let i = 0; i < 5; i++) {
  2. if (i == 3) break;
  3. console.log("The number is " + i);
  4. /* 只
输出 0 , 1 , 2 , 到3就跳出循环了 */ } for (let i = 0; i <= 5; i++) { if (i == 3) continue; console.log("The number is " + i); /* 不输出3,因为continue跳过了,直接进入下一次循环 */ }

2.遍历方法

  • 假数据

  1. const temporaryArray = [6,2,3,4,5,1,1,2,3,4,5];
  2. const objectArray = [
  3. {
  4. id: 1,
  5. name: 'd'
  6. }, {
  7. id: 2,
  8. name: 'd'
  9. }, {
  10. id: 3,
  11. name: 'c'
  12. }, {
  13. id: 1,
  14. name: 'a'
  15. }
  16. ];
  17. const temporaryObject = {
  18. a: 1,
  19. b: 2,
  20. c: 3,
  21. d: 4,
  22. };
  23. const length = temporaryArray.length;
  • 普通for循环遍历

  1. for(let i = 0; i < length; i++) {
  2. console.log(temporaryArray[i]);
  3. }
  • for in 循环

  1. /* for in 循环主要用于遍历普通对象,
  2. * 当用它来遍历数组时候,也能达到同样的效果,
  3. * 但是这是有风险的,因为 i
输出为字符串形式,而不是数组需要的数字下标, * 这意味着在某些情况下,会发生字符串运算,导致数据错误 * */ for(let i in temporaryObject) { /* hasOwnProperty只加载自身属性 */ if(temporaryObject.hasOwnProperty(i)) { console.log(temporaryObject[i]); } }
  • for of 循环,用于遍历可迭代的对象

  1. for(let i of temporaryArray) {
  2. console.log(i);
  3. }
  • forEach 第一个值为数组当前索引的值,第二个为索引值,只能遍历数组,无返回值,也无法跳出循环

  1. let a = temporaryArray.forEach(function(item, index) {
  2. console.log(index, item);
  3. });
  • map 返回新数组,只能遍历数组

  1. temporaryArray.map(function(item) {
  2. console.log(item);
  3. });
  • filter 是数组的内置对象,不改变原数组,有返回值

  1. temporaryArray.filter(function(item) {
  2. console.log(item%2 == 0);
  3. });
  • some判断是否有符合的值

  1. let newArray = temporaryArray.some(function(item) {
  2. return item > 1;
  3. });
  4. console.log(newArray);
  • every判断数组里的值是否全部符合条件

  1. let newArray1 = temporaryArray.every(function(item) {
  2. return item > 6;
  3. });
  4. console.log(newArray1);
  • reduce(function(total, currentValue, currentIndex, array) {}, [])

total:初始值或者计算结束后的返回值, currentValue遍历时的当前元素值,currentIndex当前索引值,array当前数组
如果没有指定参数-空数组[],累积变量total默认是第一个元素的值
在指定参数空数组后,累积变量total的初始值就变成了空数组

  1. let temporaryObject3 = {};
  2. let newArray2 = objectArray.reduce(function(countArray, currentValue) {
  3. /* 利用temporaryObject3里存放id来判断原数组里的对象是否相同,若id相同,则继续下一步,不同则将该对象放入新数组中
  4. * 则countArray为去重后的数组
  5. * */
  6. temporaryObject3[currentValue.id] ? '' : temporaryObject3[currentValue.id] = true && countArray.push(currentValue);
  7. return countArray;
  8. }, []);
  9. console.log(newArray2);

以上就是javascript遍历方法的介绍(代码示例)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行