H. *_*lyn -4 arrays prototype node.js ecmascript-6
我将Array在我的Node.JS服务器应用程序中选择一个随机元素.我也使用ES6的箭头语法.在对象的原型中,我添加了一个名为的函数random().您可以在下面找到我的代码:
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
};
Run Code Online (Sandbox Code Playgroud)
但是我调试代码我发现关键字this给了我一个空对象.在观察列表中我添加了值arr,我看到了:
但是,该数组包含两个元素,两个表示API键的字符串.
我的代码出了什么问题?
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |