1

I made this code to check out how "random" the random function is.

Array.prototype.random = function() {
  var index = Math.floor(this.length*Math.random());
  return this[index];
}
var arr = new Array('a', 'b', 'c', 'd', 'e');

var count = [0, 0, 0, 0, 0]; //I want to ask about this part

for (var i = 0; i < 10000; i++) {
  var val = arr.random();
  console.log(val);

  switch (val) {
    case 'a':
      count[0]++;
      break;
    case 'b':
      count[1]++;
      break;
    case 'c':
      count[2]++;
      break;
    case 'd':
      count[3]++;
      break;
    case 'e':
      count[4]++;
      break;
  }
}

for (var i = 0; i < count.length; i++) console.log(count[i]);    

In the process, I couldn't think of better way to initialize the 'count' array. Using that way, it would get really repetitive. I would have to put thousand 0 if my 'arr' has 1000 elements. Can anybody suggest better way for me?

If I don't initialize each element of 'count' array as 0, I get NaN.

Lemile
  • 45
  • 3

4 Answers4

1

I'm not exactly sure if that's what you're asking about, but if you want to initialize an array with 1000 same entries, all you need to do is:

var count = new Array(1000).fill(0)
Michał Sadowski
  • 1,946
  • 1
  • 11
  • 24
1

You could do the following

var temp = new Array(1000);
var count = temp.fill(0); 
safwanmoha
  • 306
  • 1
  • 2
  • 11
1

You can use the Array#fill() method. For example, to create an array of size 12 entirely filled up with 10s, you can use the following:

const array = new Array(12).fill(10)
console.log(array)

Here's some more documentation on this method.

kognise
  • 612
  • 1
  • 8
  • 23
0

If you just need to loop over the arguments passed into the function you can access them with the arguments keyword.