我来自C#。一个小例子与C#语法:这个技术叫什么?
// using System.Linq;
int[] array = { 1, 2, 3, 5 };
int result = array.SingleOrDefault(x => x % 2 == 0);
我想这句法convert
到JavaScript语法:
Array.prototype.singleOrDefault = function (tsource) {
\t var $self = this
\t if ($self.length) {
\t for (let i = 0; i < $self.length; i++) {
\t if (tsource($self[i])) {
\t return $self[i]
}
}
return null
}
};
var test = function() {
var array = [1, 2, 3, 5];
var result = array.singleOrDefault(x => x % 2 === 0)
if (result !== null) {
\t alert(result)
}
};
<button onclick="test()">Click me</button>
在C#:.SingleOrDefault(TSource)
叫Linq method
从System.Linq
命名空间引用。
所以,我的问题是:什么是在这种情况下(在JavaScript中)叫.singleOrDefault(x => x % 2 === 0)
?
lambda表达式?匿名函数? –
其猴子修补功能。 –
你在问什么函数像'.singleOrDefault()'被调用,或者调用了什么'x => x%2 === 0'部分,或者...? (顺便说一句,你的函数看起来和标准数组['.find()'方法]基本一样(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/ Array/find)。) – nnnnnn