简体   繁体   English

Array.filter 也能够 map 对象数组是否正常?

[英]Is it normal for Array.filter to also be able to map an array of objects?

Not sure if this is really a question but I noticed this when I accidentally didn't use an equality check when using Array.filter.不确定这是否真的是一个问题,但是当我在使用 Array.filter 时不小心没有使用相等检查时,我注意到了这一点。 Instead, it mapped my array when I feel like I should've received some kind of error for not using the equality check:相反,当我觉得我应该因为不使用相等检查而收到某种错误时,它映射了我的数组:

const x = [{ name: 'user' }];
console.log(x.filter(x => x.name = 'another user'))

// Result:
// [{ name: 'another user' }]

Is this documented anywhere?这在任何地方都有记录吗? I feel like this isn't intended.我觉得这不是故意的。 I couldn't find anything about Array.filter also being able to map so that's why I ask it here.我找不到任何关于 Array.filter 也能够 map 所以我在这里问它的原因。 Maybe this belongs on github...也许这属于 github...

There are many array methods which may well iterate over all elements of the array unless stopped earlier somehow (such as through a thrown error, or through a falsey value returned by the callback to Array.every , or through a truthy value returned by the callback to Array.find ).有许多数组方法可以很好地迭代数组的所有元素,除非以某种方式提前停止(例如通过抛出的错误,或者通过回调返回的虚假值Array.every ,或者通过回调返回的真实值到Array.find )。

These methods can all be misused to do something they weren't designed for.这些方法都可能被滥用来做一些他们不是为之设计的事情。 There are no exceptions, except perhaps for the generic iteration methods which were designed for side-effects.没有例外,除了为副作用设计的通用迭代方法。

Yes, you can misuse .filter as a substitution for a generic iteration method by performing side-effects inside the callback.是的,您可以通过在回调中执行副作用来滥用.filter作为通用迭代方法的替代。 You can also, for example, misuse .map the same exact way.例如,您也可以以完全相同的方式滥用.map

If you want to be able to protect yourself against these sorts of typos, consider using a linter which will warn you against it - such as with ESLint's no-return-assign .如果您希望能够保护自己免受此类拼写错误的影响,请考虑使用 linter 来警告您,例如使用 ESLint 的no-return-assign

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM