Sunday, November 28, 2021

Arrays in javascript

 N.B- we can iterate an array using foreach and map in javascript like below-

var arrays = [1,2,3,4,5];

//foreach

arrays.forEach(function(cur){

    if(cur===1){

        break; //break and continue is illegal in foreach .

   }    console.log(cur);

});

//map

arrays.map(function(cur){

    if(cur===2){

        break;////break and continue is illegal in map.

    }

    console.log(cur);

});

so the solution is to use regular for loop-

//ES5

for(var i=0;i<arrays.length;i++){

    if(i===3){

        break;

    }

    console.log(arrays[i]);

}

//ES6

const arrays = [7,1,2,3,4,5];

for(const cur of arrays){

    if(cur===3){

        continue;

    }

    console.log(cur);

}

we can use for--of loop to iterate easily over an array in ES6.



No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...