温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

javascript如何遍历方法

发布时间:2020-12-08 14:07:44 来源:亿速云 阅读:139 作者:小新 栏目:web开发

这篇文章主要介绍了javascript如何遍历方法,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

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

1. 终止或者跳出循环

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

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

  • return 终止函数执行

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

2.遍历方法

  • 假数据

const temporaryArray = [6,2,3,4,5,1,1,2,3,4,5];
const objectArray = [
    {
        id: 1,
        name: 'd'
    }, {
        id: 2,
        name: 'd'
    }, {
        id: 3,
        name: 'c'
    }, {
        id: 1,
        name: 'a'
    }
];
const temporaryObject = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
};
const length = temporaryArray.length;
  • 普通for循环遍历

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

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

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

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

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

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

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

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

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

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

感谢你能够认真阅读完这篇文章,希望小编分享javascript如何遍历方法内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI