JavaScript中怎么使用for循环语句

这篇文章主要讲解了“JavaScript中怎么使用for循环语句”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JavaScript中怎么使用for循环语句”吧!

创新互联建站-专业网站定制、快速模板网站建设、高性价比宝应网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式宝应网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖宝应地区。费用合理售后完善,10多年实体公司更值得信赖。

for

这大概是应用最广的循环语句了吧,简单实用,且大多数时候性能还是在线的,唯一的缺点大概就是太普通,没有特色,导致很多人现在不愿用它。

const array = [4, 7, 9, 2, 6];
for (let index = 0; index < array.length; index++) {
    const element = array[index];
    console.log(element);
}
// 4, 7, 9, 2, 6

for...in

for...in 语句可以以任意顺序遍历一个对象的除 Symbol 以外的可枚举属性。

const temp = {name: "temp"};
function Apple() {
    this.color = 'red';
}

Apple.prototype = temp;

const obj = new Apple();

for (const prop in obj) {
    console.log(`obj.${ prop } = ${ obj[prop] }`);
}

// obj.color = red
// obj.name = temp

如果你只要考虑对象本身的属性,而不是它的原型,那么使用  getOwnPropertyNames() 或执行 hasOwnProperty() 来确定某属性是否是对象本身的属性。

const temp = {name: "temp"};
function Apple() {
    this.color = 'red';
}

Apple.prototype = temp;

const obj = new Apple();

for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        console.log(`obj.${ prop } = ${ obj[prop] }`);
    }
}

// obj.color = red

当然,也可以用来遍历数组。

const arr = [1, 2, 3, 4, 5];
for (const key in arr) {
    console.log(key)
}
// 0,1,2,3,4

使用 for...in 可以遍历数组,但是会存在以下问题:

  1. index 索引为字符串型数字(注意,非数字),不能直接进行几何运算。

  2. 遍历顺序有可能不是按照实际数组的内部顺序(可能按照随机顺序)。

所以一般不建议使用 for...in 来遍历数组。

for...of

for...of 语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。

const array = ['a', 'b', 'c'];
for (const element of array) {
    console.log(element);
}

// a
// b
// c

for...of 和 for...in 的区别:

  • for...in 语句以任意顺序迭代对象的可枚举属性。

  • for...of 语句遍历可迭代对象定义要迭代的数据。

Object.prototype.objCustom = function () { };
Array.prototype.arrCustom = function () { };

let iterable = [3, 5, 7];
iterable.foo = 'hello';

for (const key in iterable) {
    console.log(key); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
// 0, 1, 2, "foo", "arrCustom", "objCustom"

for (const key of iterable) {
    console.log(key);
}
// 3, 5, 7

使用 for...of 遍历 Map 结构:

let nodes = new Map();
nodes.set("node1", "t1")
    .set("node2", "t2")
    .set("node3", "t3");

for (const [node, content] of nodes) {
    console.log(node, content);
}
// node1 t1
// node2 t2
// node3 t3

可以看出,使用 for...of 遍历 Map 结构还是挺方便的,推荐使用!

感谢各位的阅读,以上就是“JavaScript中怎么使用for循环语句”的内容了,经过本文的学习后,相信大家对JavaScript中怎么使用for循环语句这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


当前名称:JavaScript中怎么使用for循环语句
当前链接:http://csdahua.cn/article/ijoisd.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流