1

I am trying to get my program to generate a 4 number pin to be used for a game.

I originally wanted to do this:

function paswdGen() {
    var nums = [0, 0, 0, 0];
    for each (var x in nums) {
        x = Math.floor((Math.random() * 9) + 1);
    }
} 
document.getElementById("nums").innerHTML = nums;

How do I use a "for each" loop in javascript without jQuery?

Roman P
  • 35
  • 3

4 Answers4

1

You'll want to use the language feature Array.prototype.forEach. Check out some great documentation from MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Here's a version of your code:

var nums = [0, 0, 0, 0];
nums.forEach(function(nums){
    x = Math.floor((Math.random() * 9) + 1);
})
Thomas Murphy
  • 1,360
  • 4
  • 14
  • 41
  • I should also add that this method call is Array-specific. There is separate functionality for object and string iteration. – Thomas Murphy Feb 05 '15 at 15:45
  • I used this but it just returned an undefined if I used something like: `document.getElementById("nums").innerHTML = nums[0];` Any advice? – Roman P Feb 05 '15 at 16:00
1

I think Array.prototype.forEach may not be what you need here, may I suggest using Array.prototype.map instead? (Note that this would work on most browsers and IE9+)

// this function would return a string of 4 digits
function paswdGen() {
    var nums = [0, 0, 0, 0];

    return nums.map(function () {
        return Math.floor((Math.random() * 9) + 1);
    }).join('');
} 
axelduch
  • 10,769
  • 2
  • 31
  • 50
0
var code = '';

for (var i = 0; i < 4; i++) {

    code += Math.floor((Math.random() * 9) + 1);
}

console.log(code); // Outputs 1234 (for example)

If your goal is to do it with a forEach:

var nums = [0, 0, 0, 0];
var code = '';

nums.forEach(function(){
    code += Math.floor((Math.random() * 9) + 1);
})

console.log(code); // Outputs 1234 (for example)
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
0

no need to create the array manually:

var length = 4;
var range = 10;

Array.apply(null, {length: length}).map(function() {
  return Math.floor((Math.random() * range) + 1);
});

An alternative way:

var length = 4;
var range = 10;
var transform = function(random) { return Math.floor(random * range) + 1 };
Array.apply(null, {length: length}).map(Math.random).map(transform)
andrusieczko
  • 2,824
  • 12
  • 23