for in
=> iterate through obj keys
obj={a:1,b:2,c:3}
for(let key in obj)
{
document.write(key) //abc
}
From MDN:
The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.
for ... in will iterate every property from the prototype chain!
The following example shows the difference between a for...of loop and a for...in loop when used with an Array.
js
Copy to Clipboard
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
const iterable = [3, 5, 7];
iterable.foo = "hello";
for (const i in iterable) {
console.log(i);
}
// "0", "1", "2", "foo", "arrCustom", "objCustom"
for (const i in iterable) {
if (Object.hasOwn(iterable, i)) {
console.log(i);
}
}
// "0" "1" "2" "foo"
for (const i of iterable) {
console.log(i);
}
// 3 5 7
for of:
From MDN: The for...of is for iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.
=> iterate through iterable items
arr=[1,2,3,4]
for(let e of arr){
document.write(e)
}
=> ! iterate through Map:
const iterable = new Map([ ["a", 1], ["b", 2], ["c", 3],]);
for (const entry of iterable) {
console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
//or iterable.entries
for (const [key, value] of iterable) {
console.log(value);
}
//whether has key
iterable.has(key)
=> iterate through arguments
function foo() {
for (const value of arguments) {
console.log(value);
}
}
foo(1, 2, 3);
// 1
// 2
// 3
=> iterate through a generator
function* source() {
yield 1;
yield 2;
yield 3;
}
const generator = source();
for (const value of generator) {
console.log(value);
}
// 1
// 2
// 3
map get values
const iterable = new Map([ ["a", 1], ["b", 2], ["c", 3],]);
document.write(Array.from(iterable.values()))
arr.forEach((item,id)=>{
return item //不会结束循环,相当于continue!! 如果需要跳出循环,写throw
})
//但是 for(let a of arr) 可以使用break跳出循环!!)