问题:
This question already has an answer here:
fill() not supported in IE11 2 answers
I'm creating a graph thanks to Chart.js, in a project of ASP.NET M...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
This question already has an answer here:
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.
回答1:
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
回答2:
Polyfill .fill()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Polyfill
if (!Array.prototype.fill) {
Object.defineProperty(Array.prototype, 'fill', {
value: function(value) {
// Steps 1-2.
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
// Steps 3-5.
var len = O.length >>> 0;
// Steps 6-7.
var start = arguments[1];
var relativeStart = start >> 0;
// Step 8.
var k = relativeStart < 0 ?
Math.max(len + relativeStart, 0) :
Math.min(relativeStart, len);
// Steps 9-10.
var end = arguments[2];
var relativeEnd = end === undefined ?
len : end >> 0;
// Step 11.
var final = relativeEnd < 0 ?
Math.max(len + relativeEnd, 0) :
Math.min(relativeEnd, len);
// Step 12.
while (k < final) {
O[k] = value;
k++;
}
// Step 13.
return O;
}
});
}
回答3:
Use map
:
var arrayBackgroundColor = Array.apply(null, Array(@Model.Data.Count())).map(function(e) {
return 'rgba(54, 162, 235, 0.2)';
});