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.

2
  • .fill() method? Commented Mar 25, 2019 at 14:49
  • Thanks! I tried! I just had to declare 'count' array differently. var count = new Array(arr.length); count.fill(0, 0); but it worked!! Commented Mar 25, 2019 at 15:07

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!! It really helped
You're welcome :) If you want, accept the answer so others who come across your question can find it.
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)

1 Comment

Thank you so much!! Helped a lot :)
1

You could do the following

var temp = new Array(1000);
var count = temp.fill(0); 

1 Comment

Thank you too :))))
0

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

1 Comment

I didn't pass any arguments this time, but I'll try using it next time. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.