Skip to main content

Difference between for...in and for...of in javascript

 In javascript, for in is a standard in ES5, used to traverse keys. for of is a standard in ES6, used to traverse values. This article mainly explains for...in and for...of difference.

iterate over objects

for...in:Can traverse itself and properties on the prototype chain, suitable for traversing objects

        const obj={
            id:1001,
            name:"aaa",
            age:100
        }
//
        Object.prototype.Hobby="sing,jump,rap,basketball";
        for(let l in obj){
            // if(obj.hasOwnProperty(l)){
console.log(l,obj[l]);//id 1001,name aaa,age 100,Hobby sing,jump...
            // }
        }
for...of:The object cannot be traversed directly, because the custom object does not implement the iterator interface, you can manually implement the interface and then traverse, or use Object.keys() to assist in the traversal, which returns an array of key names of all enumerable properties of the object itself
const obj={
            id:1001,
            name:"aaa",
            age:100
        }
        obj[Symbol.iterator]=function(){
            // let that=this;
            let keys=Object.keys(this);
            let index=0;
            let result={};
            return {
     /*            next(){
                    if(index<keys.length){
                        result={value:that[keys[index]],done:false};
                    } */
                    next:()=>{
                    if(index<keys.length){
                        result={value:this[keys[index]],done:false};
                        // result={value:keys[index],done:false};

                    }
                    else{
                        result={value:undefined,done:true}
                    }
                    index++;
                    return result;
                }
            }
        }
        //
        Object.prototype.Hobby="sing,jump,rap,basketball";
        for(let l of obj){
            console.log(l)//1001,aaa,100
        }
        console.log(typeof Object.keys(obj));//object
        console.log(Object.keys(obj) instanceof Array);//true
console.log(Object.prototype.toString.call(Object.keys(obj)));//[object Array]
        for(let key of Object.keys(obj)){
            console.log(key,obj[key]);//id 1001,name aaa,age 100
        }

iterate through the array

for...in:It will traverse all the enumerable properties of the array, including the properties on the prototype, it is best not to use it to traverse the array, there will be an abnormal order problem, and the returned index value (index) is a string type.

 Array.prototype.mydata=5;
        let arr=[1,2,3,4];
        arr.push(100)
        for(let i in arr){
            console.log(i,arr[i],typeof i)//0 1 string
                                          //1 2 string
                                          //2 3 string
                                          //3 4 string
                                          //4 100 string
                                          //mydata string

for...of:

Array.prototype.mydata=5;
        let arr=[1,2,3,4];
        arr.push(100)   
for(let i of arr){
            console.log(i,typeof i)//0 1 string
                                          //1 number
                                          //2 number
                                          //3 number
                                          //4 number
                                          //100 number
                                         
        }

iterate over the string:

for...in:

        let str="hello";
        String.prototype.mydata="sing";
        for(let i in str){
            console.log(i,str[i])         //0 h
                                          //1 e
                                          //2 l
                                          //3 l
                                          //4 o
                                          //mydata sing
        }

for...of:

        let str="hello";
        String.prototype.mydata="sing";
        for(let i of str){
            console.log(i)//h
                          //e
                          //l
                          //l
                          //o
        }

After the release of ES5, you can also use forEach to traverse the array. forEach only traverses the elements written in square brackets, and can operate on both key and value. The type of key is number.

        let arr=["aaa","bbb","ccc"];
        arr.forEach((value,index)=>{    
            console.log(index,value);    
            if(index===1){
                // break;//err!!!
                // continue;//err!!!
                return;//√
            }
            console.log(index+"--after")
        })
for
        var arr=[1,2,3,4,5];
        for(var i=0;i<=4;i++){
            console.log(i);
            if(i===3){
                // break;
                // return;//Uncaught SyntaxError: Illegal return statement
                continue;
            }
            console.log(i,"---***")
        }
 var arr=[1,2,3,4,5];
        for(let i in arr){
            console.log(i,arr[i]);
            if(i==="3"){
                // break;
                // continue;
                return;//Uncaught SyntaxError: Illegal return statement
            }
            console.log(i+"****");
        }

Finally to sum up:

In for, for-in, break and continue can be executed normally and achieve the desired result, but return cannot be executed normally. In forEach, map, and filter, break and continue cannot be executed normally, and return only ends the current loop, not the entire function. for-of can simply and correctly traverse an array, which is the most concise and direct syntax for traversing the elements of an array. Nicely sidesteps all the pitfalls of for-in loops. It responds to break, continue and return statements correctly and flawlessly.




Comments

Popular posts from this blog

What is the difference between width property 100% and auto in css?

 width:auto: The default width value of block-level elements. When set to this value, the browser will automatically select an appropriate width value to adapt to the width of the parent element. When the width is set to 100%, the width of the child element box The value is equal to the parent's content, and as the parent's content automatically changes, after adding the padding and margin of the child element, its width remains unchanged, which is the difference from setting it to auto. But we most often use width:auto, because it is more flexible, width:100% is used less, because when adding padding or margin, this method is easy to make it exceed the parent box and destroy the original layout.

Access to XMLHttpRequest at 'http://localhost:8080/xxx' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 Due to browser same-origin policy restrictions. The Same Origin Policy is a convention. This is the main and essential security feature of the browser. Without the same-origin policy, normal browser functionality may be affected. The web is built on the same-origin policy, and browsers are just one implementation of the same-origin policy. The Same Origin Policy prevents JavaScript scripts from one domain from interacting with content from another domain. The so-called same origin (that is, the same domain) means that two pages have the same protocol, host and port.