关于javascript:前端-JavaScript-中的三种-for-循环语句总结

1次阅读

共计 2030 个字符,预计需要花费 6 分钟才能阅读完成。

JavaScript 中的 for 循环语句置信大家都曾经快用厌了,当初有好多文章都在讲怎么缩小代码中的 for 循环语句,然而,你又不得不抵赖它们真的很有用。明天,我来总结一下前端 JavaScript 中三种 for 循环语句。

for

这大略是利用最广的循环语句了吧,简略实用,且大多数时候性能还是在线的,惟一的毛病大略就是 太普通,没有特色,导致很多人当初不愿用它。

const array = [4, 7, 9, 2, 6];
for (const 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...offor...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 构造还是挺不便的,举荐应用!

总结

  1. 如果一般 for 循环用腻了,举荐应用 for...of 来代替。
  2. 这三种循环都能够应用 break 关键字来终止循环,也能够应用 continue 关键字来跳过本次循环。
  3. for...of 循环的适用范围最大。

~

~ 本文完,感激浏览!

~

学习乏味的常识,结识乏味的敌人,塑造乏味的灵魂!

我是〖编程三昧〗的作者 隐逸王,我的公众号是『编程三昧』,欢送关注,心愿大家多多指教!

你来,怀揣冀望,我有墨香相迎!你归,无论得失,唯以余韵相赠!

常识与技能并重,内力和外功兼修,实践和实际两手都要抓、两手都要硬!

正文完
 0