一文搞懂 js 中的各种 for 循环的不同之处 All In One
一文搞懂 js 中的各种 for 循环的不同之处 All In One
for
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-07-01
* @modified
*
* @description for : var hoisting, break loop, support array-like loop
* @augments
* @example
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
*
*/
const log = console.log;
const arr = [1, 2, 3, 4];
const obj = {
a: "A",
b: "B",
c: "C",
};
for (var index = 0; index < 3; index++) {
log(`index`, index)
}
// index 0
// index 1
// index 2
log(`hoisting index`, index)
// hoisting index 3
for (let indexLet = 0; indexLet < 3; indexLet++) {
log(`indexLet`, indexLet)
}
// indexLet 0
// indexLet 1
// indexLet 2
try {
log(`not hoisting index`, indexLet);
// ReferenceError: indexLet is not defined
} catch (error) {
log(`js ❌`)
}
for (let i = 0; i < arr.length; i++) {
if (i === 3) {
log(`🧇break for`);
break;
} else {
log(`index ${i} =`, arr[i]);
}
}
// index 0 = 1
// index 1 = 2
// index 2 = 3
// 🧇break for
const entries = Object.entries(obj);
log(`entries =`, entries)
// [ [ 'a', 'A' ], [ 'b', 'B' ], [ 'c', 'C' ] ]
const keys = Object.keys(obj);
log(`keys =`, keys)
// [ 'a', 'b', 'c' ]
const values = Object.values(obj);
log(`values =`, values)
// [ 'A', 'B', 'C' ]
for (let i = 0; i < keys.length; i++) {
if (i === 2) {
log(`🧇break for`);
break;
} else {
log(`index ${i} =`, obj[keys[i]]);
}
}
// index 0 = A
// index 1 = B
// 🧇break for
try {
const fragment = document.createElement(`fragment`);
const html = `
<div data-uid="div1">div 1</div>
<div data-uid="div2">div 2</div>
<div data-uid="div3">div 3</div>
`;
fragment.insertAdjacentHTML(`beforeend`, html);
const divs = fragment.querySelectorAll(`[data-uid^="div"]`);
// NodeList(3) [div, div, div]
typeof divs;
// "object"
for (let i = 0; i < divs.length; i++) {
log(`divs[i] =`, divs[i])
}
// divs[i] = <div data-uid="div1">div 1</div>
// divs[i] = <div data-uid="div2">div 2</div>
// divs[i] = <div data-uid="div3">div 3</div>
} catch (error) {
log(`DOM ❌`)
}
for in
for...in & break
const log = console.log;
const arr = [1, 2, 3, 4];
const obj = {
a: "A",
b: "B",
c: "C",
};
for (const key in obj) {
log(`key =`, key);
}
for (const key in obj) {
if(key === 'b') {
log(`key =`, key);
break;
}
log(`key =`, key);
}
for of
for...of & break
const log = console.log;
const arr = ['a', 'b', 'c', 'd'];
for (const item of arr) {
log(`item =`, item);
}
for (const item of arr) {
if(item === 'b') {
log(`item =`, item);
break;
}
log(`item =`, item);
}
forEach
map
reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
filter
find
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13287257.html
未经授权禁止转载,违者必究!