foreach over array javascript
/** 1. Use forEach and related */
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
/** 2. Use a simple for loop */
var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
console.log(a[index]);
}
/**3. Use for-in correctly*/
// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
if (a.hasOwnProperty(key) && // These checks are
/^0$|^[1-9]\d*$/.test(key) && // explained
key <= 4294967294 // below
) {
console.log(a[key]);
}
}
/** 4. Use for-of (use an iterator implicitly) (ES2015+) */
const a = ["a", "b", "c"];
for (const val of a) {
console.log(val);
}
/** 5. Use an iterator explicitly (ES2015+) */
const a = ["a", "b", "c"];
const it = a.values();
let entry;
while (!(entry = it.next()).done) {
console.log(entry.value);
}
var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
console.log(color);
});Used to execute the same code on every element in an array
Does not change the array
Returns undefined
Also in JavaScript:
- javascript search on docuemt for text on iframe
- angular two datepickers
- callback in js
- split and join in node js
- nodejs express routing get
- how to pause useState counter value react hoooks
- tilt js vue
- after click text editior open in javascript
- pandas show column with regular expression
- "Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it"
- jquery create element
- html to pdf javascript
- if i pass an object to a function is it the same object javascript
- remove floating point javascript
- random number in js
- javascript open pdf in new tab
- javascript get text between two words
- How to Set focus to first text input in a bootstrap modal after shown
- Javascript clear canvas
- javascript append how first element
- change version webpack-dev-middleware
- check if outside the div is clicked
- checking ascii in js
- javascript change frame background