How to call a function for each array element in JavaScript

2 Answers

0 votes
<button onclick="marks.forEach(myFunction)">Click</button>
var marks = [78, 92, 100, 86];

function myFunction(item, index) {
    document.write("arr[" + index + "] = " + item + "<br>");
}


/*

run:

arr[0] = 78
arr[1] = 92
arr[2] = 100
arr[3] = 86

*/

 



answered Apr 5, 2017 by avibootz
0 votes
var marks = [78, 92, 100, 86];

marks.forEach(myFunction)

function myFunction(item, index) {
    document.write("arr[" + index + "] = " + item * 2 + "<br>");
}


/*

run:

arr[0] = 156
arr[1] = 184
arr[2] = 200
arr[3] = 172

*/

 



answered Apr 5, 2017 by avibootz
...