The for loop
For (loop start condition; Cycle termination condition; Condition for each loop to accumulate){loop body code};
var i = 0;
=> Global variables, which can be omitted (if initial values have been set globally)let i = 0;
=> let forms the block-level scope, and I is the private variable in the block-level scope
let ary = [10.20.30]
for (var i = 0; i < ary.length; i++) {
console.log(ary[i]); / / 10 20 to 30
console.log(typeof i); //number
};
Copy the code
Two keywords in the for loop (for flow control) : break continue
break:
The loop is forced to end, and the following code is no longer executedcontinue:
When the current cycle ends, the code following the contiune is no longer executed and the next cycle continues
num = 0;
for (var i = 0; i < 10; i++) {
if (i < 5) {
num++;
continue;
};
if (i === 5) {
num--;
break;
};
num *= 2;
};
console.log(num); / / 4
Copy the code
Second, for in loop
- For in is used to loop through the enumerable properties of the current object
- Enumerable: Traversable
- 1. The private (self-written) attributes of an object are enumerable
- 2. Browser built-in properties are generally non-enumerable (e.g
__pproto__
) - 3. The attributes you set on the prototype of the class are also enumerable, and for in is also iterated (generally, you do not want to iterate through the public attributes on the prototype), so it is usually added to the code first
if(obj.hasOwnProperty(key){ // When we use "for in" to iterate over an object, we add a private attribute validation console.log(key) } Copy the code
- The for in loop has its own order, traversing numeric attribute names (in descending order) and string attribute names (in written order)
// Loop over an object
let obj = { name: 'Tom'.age: 23.id: 6 };
for (let keys in obj) {
console.log(keys); // name age id
console.log(obj[keys]); // Tom 23 6;
console.log(typeof keys); //string
};
Copy the code
// Loop over an array
let ary = [10.20.30];
for (let keys in ary) {
console.log(keys); // name age id
console.log(ary[keys]); // Tom 23 6;
console.log(typeof keys); // string
};
Copy the code
let obj = {
zdy: 'Tom'.// Private attributes
id:13.// Private attributes
};
Object.prototype.say = function(){ // Public properties, that is, property methods on the stereotype
console.log(1);
};
for(let attr in obj){
Attr is executed if obj's private property is true
if(obj.hasOwnProperty(attr)){
console.log(obj[attr])
}
}
Copy the code
The difference between a for loop and a for in loop:
- The for loop is usually used to loop through an array, where the index I is the number data type
- The for in loop is usually used to loop over an enumerable property of an object. 2.1 When loop through an array, loop out index I is a string and cannot be used directly, which reduces code execution efficiency
ForEach loop
- For Each loop: A built-in array traversal method used to loop through arrays.
- Two parameters:
- First argument: function -> function(){} function(each value in array, index value, whole array){}
- Second argument: change this to refer to whatever is written (if null,undefined is still window)
- The forEach loop returns no value
- ForEach will loop through all elements without breaking conditions, i.e., no breaks or continues
If you want to break out of a forEach loop, you can use the try catch statement try… Catch tests for errors in code. The try section contains the code to run, while the catch section contains the code to run when an error occurs.
let arr = [true.'haha'.10, {},1.2.3]];
arr.forEach(function (item, i, all) {
// console.log(item); // Each item in the array
// console.log(i); / / index
// console.log(all); // The entire array
console.log(this); // If there is no second argument, this is the window
}, arr);
Copy the code
try {
var array = ["first"."second"."third"."fourth"];
array.forEach(function (item, index) {
if (item == "third") {
var a = aaaa; // The first second is an error
throw new Error("ending");// An error is reported, and the loop is broken
} else {
console.log(item);
};
});
} catch (e) {
if (e.message == "ending") {
console.log("It's over.");
} else {
console.log(e.message);
};
};
Copy the code
4. Map loop
Map loop: A built-in array traversal method that returns a new array
- Function (item, I,all){return each item of the new array};
var ary = [1.2.3.4.5];
var a2 = ary.map(function (item, index, ary) {
// item Indicates the current item
// index Indicates the index of the current item
// ary the original array ary === a
return item * 2; // Each time the specified return value is used as the contents of the new array
});
console.log(a2);/ /,4,6,8,10 [2]
Copy the code
5, For of cycle
For of loop: new statement in Es6 for… The scope for the of loop includes arrays, Set and Map structures, some array-like objects (such as Arguments objects, DOM NodeList objects), Generator objects, and strings.
// loop array
let arr = [true.'haha'.10, {},1.2.3]].for(let item of arr){
if(typeof item === 'number') {console.log(item); / / 10
continue;
};
if(typeof item === 'object') {console.log(item); / / {}
break;
};
console.log(item); // true haha
};
Copy the code
// Loop string
let str = 'hello';
for(let item of str){
console.log(item); // h e l l o
};
Copy the code
// Loop an array of classes
function fn() {
for (let item of arguments) {
console.log(item); // Jewel-eyed cat belly cat tail
};
};
fn('Jewel eye'.'Cat belly'.'Cat tail');
Copy the code
// For of cannot iterate directly over objects, you can use object.keys ()
// object.keys () takes all the property names in the Object and places them in an array
let obj = { name: 'Tom'.age: 33.id: 6 };
for (let item of Object.keys(obj)) {
console.log(item + ':' + obj[item]); // name:Tom age:33 id:6
};
Copy the code
The while loop
While (loop condition){// loop as long as the condition is true};
var n = 0;
while (n < 5) {
console.log(n);// The loop continues as long as the condition is true
n++;
};
Copy the code
// go through the number group
let ary = ['a'.'b'.'c'.'d'];
let i = 0;
while (ary[i]) {
console.log(ary[i]);
i++;
};
Copy the code
Do while loop
The do/while loop is a variant of the while loop. The loop executes a block of code once before checking if the condition is true, and then repeats the loop if the condition is true.
- Do {code to execute} while (condition);
let ary = ['a'.'b'.'c'.'d'];
let i = 0;
do {
console.log(ary[i]);
i++;
}
while(ary[i]);
Copy the code
8. Filter: Array filtering
- The filter of the array, the value of the filter condition
- Function (item, I,all){return (item, I,all)}
- The function returns a filtered new array
// Filter numbers greater than 10 and less than 30
let arr = [3.10.18.38.48.26];
let ary = arr.filter(function (item, i) {
return item >= 10 && item < 30
})
console.log(ary);
Copy the code
Some: checks whether an element in an array satisfies a specified condition
- Checks whether an item in the array meets a condition, and returns true as long as one condition is met; If all conditions fail, return false, a Boolean value
- Some () does not check for empty arrays.
- Some () doesn’t change the original array.
let arr = [1.2.3.4.5];
// Check if there is 6 in the array. If there is no 6, return false
let res = arr.some(function (item) {
return item === 6
});
console.log(res); // flase(array without 6)
let res1 = arr.indexOf(6);
console.log(res1); //-1(no 6 in array)
Copy the code
Every: Checks whether each item in the array satisfies the specified condition
- Check if every item in the array meets some condition, return true for all items, and false for any item that does not
- Function (item, I, all) {return}
let arr = ['62'[],NaN, {},function(){}) (), / ^ $/,2333];
let arr1 = [1.2.3.4.5.6];
let res = arr.every(function(item,i){
return item;
});
let res1 = arr1.every(function(item,i){
return item;
});
console.log(res); //false (not all items are true)
console.log(res1); //true (all items are true)
Copy the code
11, the Object. The keys () & Object. GetOwnPropertyNames ()
Object.keys()
Iterating over an object returns an array of object property names (enumerable property names)Object.getOwnPropertyNames()
- Keys getOwnPropertyNames is a built-in property on the Object base class
- But object. keys cannot return non-enumerable properties; Object. GetOwnPropertyNames can return an enumeration of attributes.
let obj = { name: 'Tom'.age: 33.id: 6 };
console.log(Object.keys(obj)); // ["name", "age", "id"]
console.log(Object.getOwnPropertyNames(obj)); // ["name", "age", "id"]
Copy the code