Javascript/forEach

解説

値を一つずつ取得

コールバック関数は「引数」として3つの値を受け取ることができる

array.forEach(function(value, index, array){}

sample1
sample1code
function s1Func(){
  var s1Array = ["aaa", "bbb", "ccc"];
  s1Array.forEach(function(value){
  	document.getElementById("s1Btn").after(value + ",");
  });
}
	
sample2
sample2code
function s2Func(){
  var s2Array = [1, 2, 3];
  s2Array.forEach(function(value, index){
  	s2Array[index] = value * 2;
  });
  console.log(s2Array);
}
	
sample3

s3p

sample3code
//span一文字ずつ囲む
function s3Func(){
  var s3p = document.querySelector("#s3p");
  var s3pText = s3p.textContent;
  s3p.innerHTML = null;
  s3pText.split('').forEach(function (c) {
    s3p.innerHTML += 'span>' + c + '/span>';
  });
}