我经常使用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()
在includes()
元素的数组上执行refundLogic
的方法。
是否有更合适的方法,例如使用扩展运算符?
顺便说一下,我知道我可能会以一种只返回true
或false
值的方式拆分我的方法,但我发现这是一种过度设计的解决方案。
答案 0 :(得分:2)
使用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);
答案 1 :(得分:1)
您可以使用Array#find函数,该函数返回传递给定条件的第一个项目。此外,filter
更快,因为filter
遍历所有项目,然后您只获得第一个项目。 find
找到第一个匹配的项目并打破循环。
从您可以看到的示例中,它迭代2次而不是3次。
const knownRefundLogics = [{
"underscoredName": "express_full_refund",
"camelized": "expressFullRefund"
}, {
"underscoredName": "express_partial_refund",
"camelized": "expressPartialRefund"
}, {
"underscoredName": "express_no_refund",
"camelized": "expressNoRefund"
}];
const foundItem = knownRefundLogics.find(item => {
console.log('Iteration');
return item.camelized === 'expressPartialRefund';
});
console.log(foundItem);
答案 2 :(得分:0)
如果你想要一个没有polyfill的解决方案,好老的循环就是你的朋友。
var knownRefundLogics = [{
"underscoredName": "express_full_refund",
"camelized": "expressFullRefund"
}, {
"underscoredName": "express_partial_refund",
"camelized": "expressPartialRefund"
}, {
"underscoredName": "express_no_refund",
"camelized": "expressNoRefund"
}];
var selected;
for(var i = 0; i < knownRefundLogics.length; i++){
let current = knownRefundLogics[i];
if(current.underscoredName === 'express_partial_refund'){
selected = current;
break;
}
}
console.log(selected);
&#13;
这样你就可以编写自己的轻质填充物。
function findInArray(array, test){
for(var i = 0; i < array.length; i++){
if(test(array[i], i, array)) return array[i];
}
}
var knownRefundLogics = [{
"underscoredName": "express_full_refund",
"camelized": "expressFullRefund"
}, {
"underscoredName": "express_partial_refund",
"camelized": "expressPartialRefund"
}, {
"underscoredName": "express_no_refund",
"camelized": "expressNoRefund"
}];
console.log(findInArray(knownRefundLogics, function(item, index, array){
return item.underscoredName === "express_partial_refund";
}));
&#13;