【发布时间】:2016-12-19 17:13:30
【问题描述】:
我将在我的 Node.JS 服务器应用程序中从 Array 中选择一个随机元素。我也使用 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
};
但是我调试代码时发现关键字this 给了我一个空对象。在监视列表中,我添加了值 arr,我看到了:
但是该数组包含两个元素,两个代表 API 密钥的字符串。
我的代码有什么问题?
【问题讨论】:
-
跳出来的第一件事是您在原型上的函数中使用粗箭头语法 - 这是故意的吗?
-
已经有了答案,所以我只评论一个细节:不要直接将属性分配给原型,使用 Object.defineProperty 以便您的属性不可枚举
-
@Daniel:我使用箭头语法是因为我使用的是 ES6。
-
@H.Pauwelyn 恐怕这是一个非常普遍的误解。胖箭头函数不仅仅是传统函数的简短语法。您可能希望阅读更多相关信息:exploringjs.com/es6/ch_arrow-functions.html
标签: arrays node.js ecmascript-6 prototype