I'll pick a random element form an Array
in my Node.JS server application. I also use the arrow syntax of ES6. In the prototype of the object I've added a function named random()
. Below you could find my code:
Array.prototype.random = () => { // --> add element to prototype of `Array` object
let rnd = Math.random(); // --> gives me a random number between 0 and 1
let len = this.length; // --> `this.length` gives `undefined`
let naam = rnd * len - 1; // --> result is `NaN`
let numb = Math.floor(naam); // --> `numb` is also `NaN`
let arr = this; // --> `arr` contains an `Object` with none
// properties or elements but `this` contains
// the elements and the length.
let el = arr[numb]; // --> `el` is `undefined`
return el; // --> returns the random picked element
};
However I debug the code I see that the keyword this
gives me an empty object. In the watch list I've added the value arr
and I see this:
However the array contains two elements, two strings that represents API keys.
What is wrong with my code?