gpt4 book ai didi

javascript - 高效访问Array.prototype.filter单项返回

转载 作者:行者123 更新时间:2023-11-30 11:29:16 25 4
gpt4 key购买 nike

我经常使用 Array.prototype.filter,我只希望一个元素为真。

由于过滤器返回结果数组,我发现自己需要始终访问该元素,所以我做了类似

knownRefundLogics.filter((refundLogic) => this.hasTag(refundLogic.underscoredName))[0]

假设:

knownRefundLogics = [{
"underscoredName": "express_full_refund",
"camelized": "expressFullRefund"
}, {
"underscoredName": "express_partial_refund",
"camelized": "expressPartialRefund"
}, {
"underscoredName": "express_no_refund",
"camelized": "expressNoRefund"
}]

hasTag() 一种方法,它在数组上为refundLogic 元素执行includes()

是否有更合适的方法来做到这一点,例如使用展开运算符?

顺便说一下,我知道我可能会以仅返回 truefalse 值的方式拆分我的方法,但我发现这个解决方案有点过度设计.

最佳答案

使用Array#find () 而不是 - 只要谓词返回 true,迭代就会停止,并立即返回匹配项(不是数组):

const knownRefundLogics = [{"underscoredName":"express_full_refund","camelized":"expressFullRefund"},{"underscoredName":"express_partial_refund","camelized":"expressPartialRefund"},{"underscoredName":"express_no_refund","camelized":"expressNoRefund"}];

const demoHasTag = (t) => t === 'express_partial_refund';

const result = knownRefundLogics.find((refundLogic) => demoHasTag(refundLogic.underscoredName));

console.log(result);

关于javascript - 高效访问Array.prototype.filter单项返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46845430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com