Search code examples
javascriptarraysecmascript-6ecmascript-5

How to create an array with certain variable length and the same value repeated without using .fill?


I'm creating a graph thanks to Chart.js, in a project of ASP.NET MVC, and in the view, I need to create an array with a value, but the length of the array is variable, I used the ".fill" and worked great, but in IE11 doesn't work so I need another way.

I have been searching the web but I haven't found any clean way to do it, and my knowledge is very limited because I have just started working with JS.

This is what I was using but doesn't work on IE11

var arrayBackgroundColor = Array(@Model.Data.Count()).fill('rgba(54, 162, 235, 0.2)');

(the @Model.Data.Count() is an integer corresponding with the length it must have)

This is the answer from IE11 on the console error

SCRIPT438: Object doesn't support property or method 'fill'

So, I would really appreciate another way of creating the desired array.


Solution

  • You can use a normal for loop

    let arrayBackgroundColor =[]; 
    
    for(var i = 0;i<@Model.Data.Count();i++){
      arrayBackgroundColor .push('rgba(54, 162, 235, 0.2)')
    });
    

    or you can use this Polyfill