昨天看到一段代码,是这样的:
const pets = [
{ type: 'Dog', name: 'Max'},
{ type: 'Cat', name: 'Karl'},
{ type: 'Dog', name: 'Tommy'},
]
function findDog(name) {
for(let i = 0; i
用短方法后:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }
我查了查arr.find方法,定义是array.find(function(currentValue, index, arr),thisValue)
上面的代码在pet=pets.find()内又传入pet,而没有参数,想知道这段代码到底是如何实现的呢?请诸大神帮解惑
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
把箭头函数转换成ES5就是这样。
find用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。这些API还是需要多查阅文档,都是基础知识不用转弯的东西。
MDN文档
es6 手册
pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');等效于
箭头函数只有一个参数的时候,小括号可以省略