Answers for "javascript foreach string"

10

js for each character in string

for (var i = 0; i < str.length; i++) {
  alert(str.charAt(i));
}
Posted by: Guest on February-19-2020
9

javascript loop through string

for (var i = 0; i < str.length; i++) {
  console.log(str.charAt(i));
}
Posted by: Guest on June-01-2020
6

For-each over an array in 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);
}
Posted by: Guest on November-27-2019
0

string foreach javascript

//for
  str='hello'
  for (var i = 0; i < str.length; i++) {
    console.info(str[i]);
  }

//for...of
  let result1 = '';
  for (let letter of str) {
    result1 += letter;
  }
  console.log(`for...of : ${result1}`)

//forEach

  // ES6 version.
    let result2 = '';
    str.split('').forEach(letter => {
      result2 += letter;
    });
    console.log(`forEach ES6 : ${result2}`)

  //or
    var result3 = '';
    str.split('').forEach(function(letter) {
      result3 += letter;
    });
    console.log(`forEach standard : ${result3}`)

//for...in
  var result4 = '';
  for (var letterIndex in str) {
    result4 += str[letterIndex];
  }
    console.log(`for...in : ${result4}`)
//map
	// ES6 version.
      var result5 = '';
      str.split('').map(letter => {
        result5 += letter;
      });
      console.log(`map ES6 : ${result5}`)
	
	//or
      let result6 = '';
      str.split('').map(function(letter) {
        result6 += letter;
      });
      console.log(`map standard : ${result6}`)
Posted by: Guest on August-24-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language