我是一名初级/中级 JavaScript 程序员,最近在工作面试中分发了一些练习。
我必须在 JavaScript 中编写一个名为 find 的函数,该函数带有两个参数,其中一个是箭头函数,包含一个参数。该函数应该在数组中找到适当的对象并返回它。我无法理解箭头函数 ((toy) => (toy.type === 'car')) 的作用、它的计算方式以及如何使用它。 toy 没有定义,如示例所示,它只是用作参数,我觉得这非常令人困惑和费解。
给出的练习:
const toys = [{type: "car", color: "red"}, {type: "ball", color: "blue"}, {type: "teddy-bear", color: "brown"}]
const carToy = find(toys, (toy) => (toy.type === 'car'));
console.log(carToy); // expected output: {type: "car", color: "red"}
我写的:
function find(array, toy) {
console.log(toy); // [Function (anonymous)]
toy(); // TypeError: Cannot read properties of undefined (reading 'type')
console.log(toy()); // TypeError: Cannot read properties of undefined (reading 'type')
}
起初我以为玩具会计算出字符串“car”,但事实并非如此。 find 函数内的 console.log() 返回未定义或 [函数(匿名)]。
如果我有一个字符串,我可以轻松解决问题,但是箭头函数让我卡住了一个多小时。我尝试在网上找到解决方案,但没有任何帮助我理解这一点。
很想获得一些关于如何解决这个问题的指导以及任何可以教我更多关于箭头函数的深入资源。
看来你需要实现 find 方法。
发生的情况是该函数作为参数传递,因此为了能够调用该函数,您需要向其传递一个类型为 toy 的对象。
function find(array, toy) {
for(var i in array) {
if(toy(array[i])
return array[i];
}
return null;
}
您可以阅读这篇文章以更详细地了解它是如何工作的