JavaScript循环的写法有哪些
时间:2022-02-11 17:16
JavaScript循环的写法有:1、“for (let index = 0; index < len; index++) {...}”方式;2、“myArray.forEach(function(index){...}”方式等等。 本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。 JavaScript循环的写法有哪些? javascript之for循环的几种写法 背景 javascript中的for循环选择多种多样,可你知道其中的差别在哪里吗?什么时候又该用哪种循环才是最佳策略?以上这些是本文想讨论的,欢迎交流。 说明 1、20年前的for循环 中规中矩。 2、forEach 缺点,没有返回值。 3、for...in 最糟糕的做法,因为此时的index是字符串,而且不一定按照数组的顺序输出,很吓人。 仅适用于遍历普通对象的key。 4、for...of 【推荐学习:javascript基础教程】 以上就是JavaScript循环的写法有哪些的详细内容,更多请关注gxlsystem.com其它相关文章!//20年前的写法
let len = myArray.Length
for (let index = 0; index < len; index++) {
console.log(myArray[index])
}
//ES5的写法
myArray.forEach(function(index){
//操作你的index,index即为数组中的元素
})
//ES5的写法,劝你慎重
for (let index in myArray) {
// 千万别这样做
console.log(myArray[index]);
}
/**ES6写法
*支持数组
*类数组对象(如:NodeList对象)
*字符串
*Map
*set
*/
for (let value of myArray) {
console.log(value);
}