我來自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