我做了一个sort函数,它将一个数组作为参数传递,返回一个新数组,其索引位置按项目名称排序。
P.E:如果输入为["dog", "cat", "tiger"]
,则预期输出为[1, 0, 2]
let sortIndexes = (a) => {
var aClone = a.slice(0);
return a.sort().map(x => aClone.indexOf(x));
}
let animals = ["dog", "cat", "tiger"];
var result = sortIndexes(animals);
console.log(result) // [1, 0, 2]
嗯,此代码有效,但我认为最好添加数组原型方法。我试试吧......
Array.prototype.sortIndexes = () => {
var aClone = this.slice(0); //Console Error in this line
return this.sort().map(x => aClone.indexOf(x));
}
let animals = ["dog", "cat", "tiger"];
var result = animals.sortIndexes();
我预计不使用原型的结果相同,但会出现此错误控制台:
Cannot read property 'slice' of undefined
谢谢!的
答案 0 :(得分:4)
这就是Arrow functions
的美丽,
<div class="node" draggable="true" ondragstart="console.log(event);">
<div class="node-header">
<div class="node-title">Gain</div>
</div>
<div class="node-body">
<div class="node-content">
</div>
<div class="node-cutout">
<div class="node-cutout-left" style="">
<span class="round top"></span>
<span class="round bottom"></span>
</div>
<div class="node-cutout-left" style="margin-top:-17px;">
<span class="round top"></span>
<span class="round bottom"></span>
</div>
<div class="node-square">
</div>
</div>
</div>
</div>
箭头功能会自动将Array.prototype.sortIndexes = function(){
var aClone = this.slice(0); //Console Error in this line
return this.sort().map(x => aClone.indexOf(x));
}
let animals = ["dog", "cat", "tiger"];
var result = animals.sortIndexes();
console.log(result); // [1, 0, 2]
绑定到其中。在您的情况下,词法范围是lexical scope
。所以window
未定义。因此它抛出错误。
主要规则是你不能通过使用bind / call / etc来使用另一个箭头函数force the scope。所以我们在决定何时使用箭头函数时必须非常小心。
答案 1 :(得分:1)
箭头函数不会将this
绑定到正在迭代的元素,而this
只是保持绑定到封闭范围:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions