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

Native ajax usage

 What is AJAX? AJAX stands for "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications for data interaction between browsers and servers. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, which allows web pages to request small amounts of information from the server instead of the entire page. AJAX describes a web application architecture that mainly uses scripts to manipulate HTTP. The main feature of AJAX applications is to use scripts to manipulate HTTP and web servers for data exchange without causing page reloads. Simply put, without reloading the entire web page, AJAX loads data in the background and displays it on the web page, which can partially refresh the page. The user has a better experience using the web page, but cannot go back.

Using ref to bind elements in Vue

 Vue provides us with a property to manipulate dom, ref. When bound to the dom element, it is used similar to the id. It is called through this.$refs, and it can also be bound to the component. It is very troublesome to obtain DOM elements in the previous native way. It needs to be obtained with such a long AP as: documentgetElementXXX/querySXXX.... Then jQuery was born to solve this pain point. The use of $("id") makes Our operation has become easier. But there are other problems, jQuery is just a library (plug-in) and cannot be used to build a framework. Now Vue can help us solve this problem. Vue also has its own method to obtain DOM, which is ref. It can get not only DOM elements but also components. If you add ref to the dom element, you can get the dom element, and if you add it to the component, you can get the component instance, and you can use the component method.

What is the difference between the box-size property content-box and border-box in the css box model?

 The box model is a very important concept in CSS layout, it includes content area, padding, border, and margin. Box models can be divided into two types: standard box models and IE box models. The box model, as the name suggests, is used to hold things, and the things it holds are the content of HTML elements. In other words, every visible HTML element is a box.