gpt4 book ai didi

JavaScript 查找数组中的单个元素

转载 作者:行者123 更新时间:2023-11-29 23:20:35 26 4
gpt4 key购买 nike

.NET 的 LINQ 包含一个运算符 .Single哪个

Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

最新版本的 JavaScript 中是否有等效项? (撰写本文时为 ECMA v8)。

我能找到的最接近的操作是 .find尽管人们必须编写自己的样板来断言恰好有一个元素匹配。

.single() 的预期功能示例:

const arr = [1, 4, 9];
arr.single(v => v > 8 && v < 10); // Returns 9
arr.single(v => v < 5); // Throws an exception since more than one matches
arr.single(v => v > 10); // Throws an exception since there are zero matches

最佳答案

Is there an equivalent in the latest version of JavaScript? (ECMA v8 at time of writing).

不,不是。

您可以更改 Array 的原型(prototype)(这是不可取的)并添加一个方法来过滤数组并返回单个找到的项目或抛出错误。

Array.prototype.single = function (cb) {
var r = this.filter(cb);
if (!r.length) {
throw 'zero match';
}
if (r.length !== 1) {
throw 'too much matches';
}
return r[0];
};

const arr = [1, 4, 9];
console.log(arr.single(v => v > 8 && v < 10)); // 9
console.log(arr.single(v => v < 5)); // exception since more than one matches
// console.log(arr.single(v => v > 10)); // exception since there are zero matches

或者您可以使用 link.js .

const arr = [1, 4, 9];
console.log(Enumerable.From(arr).Single(v => v > 8 && v < 10)); // 9
console.log(Enumerable.From(arr).Single(v => v < 5)); // exception since more than one matches
// console.log(Enumerable.From(arr).Single(v => v > 10)); // exception since there are zero matches
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

关于JavaScript 查找数组中的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50853114/

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