0
Q:

how to cycle through an array js

array = [ 1, 2, 3, 4, 5, 6 ]; 
for (index = 0; index < array.length; index++) { 
    console.log(array[index]); 
} 
10
for (var key in validation_messages) {
    // skip loop if the property is from prototype
    if (!validation_messages.hasOwnProperty(key)) continue;

    var obj = validation_messages[key];
    for (var prop in obj) {
        // skip loop if the property is from prototype
        if (!obj.hasOwnProperty(prop)) continue;

        // your code
        alert(prop + " = " + obj[prop]);
    }
}
1
// Requiring the lodash library 
// src: https://lodash.com/docs/4.17.15#forEach

// console:  npm i --save lodash
const _ = require("lodash")

// Use of _.forEach() method

_.forEach([1, 2], function(value) {
  console.log(value)
});
// => Logs `1` then `2`.

// traversing an object
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key)
})
// => Logs 'a' then 'b' (iteration order is not guaranteed).

//////////////// To not use lodash ////////////////
// src: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element)
}
[2, 5, 9].forEach(logArrayElements)
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9
0

Tags

New to Communities?

Join the community