I need to list objects and I have used the following function that is in jQuery. Is there an alternative to this in JavaScript only?
$.each(object, function(index, value) {
console.log(value);
});
I need to list objects and I have used the following function that is in jQuery. Is there an alternative to this in JavaScript only?
$.each(object, function(index, value) {
console.log(value);
});
Basically this is it:
for (var key in object) {
console.log(object[key]);
}
You might want to improve if you are picking up unwanted members:
for (var key in object) {
if (object.hasOwnProperty(key)) {
console.log(object[key]);
}
}
Although technically to have the same semantics would have to do this:
object.forEach(function(value, index) {
console.log(value);
});
Works in all modern browsers, but not all use a modern, use with care.
/ p>
To iterate through an array you can use native .forEach()
or a for loop if you need to support IE8.
object.forEach(function(value, index){
console.log(value);
// fazer mais algo com o valor
});
or for older browsers:
for (var i = 0; i < object.length; i++){
var value = object[i];
var index = i; // desnecessário, mas coloquei para clarificar
console.log(value);
}
ecmascrip6:
array.forEach((item)=>{
console.log(item);
});