JS:作为参数传递给方法的函数从哪里获取参数?
JS: Where do functions passed as arguments to methods get their arguments from?
我突出显示了我不明白它的值从何而来的参数。数组不应该通过吗?这没有道理。这一切都让人感觉倒退。数组值如何进入 ages.some(checkAdult)
调用?点之前的关键字是否变成了我想象中应该在 checkAdult
之后括号中的参数?
为什么它不去 some(checkAdult(ages))
?
为什么要将它附加到带点的内容的末尾?
var ages = [3, 10, 18, 20];
function checkAdult(age) { // THIS LINE HERE, how does it link to the array???
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.some(checkAdult);
}
<p>Click the button to check if any of the elements in the array has a value of 18 or more.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
通常(但不总是)user-supplied 函数由 higher-order 函数调用。
在下面的示例中,some
对 t
的每个元素调用 f
,直到找到第一个真实结果。否则返回错误结果。
const some = (f, t) =>
t.length === 0
? false
: Boolean(f(t[0])) // f gets called by some
|| some(f, t.slice(1))
console.log(some(v => v > 30, [ 10, 20, 30, 40 ]))
// true
console.log(some(v => v > 99, [ 10, 20, 30, 40 ]))
// false
或同一程序的迭代版本 -
function some (f, t)
{ for (const v of t)
if (Boolean(f(v)))
return true
return false
}
console.log(some(v => v > 30, [ 10, 20, 30, 40 ]))
// true
console.log(some(v => v > 99, [ 10, 20, 30, 40 ]))
// false
我突出显示了我不明白它的值从何而来的参数。数组不应该通过吗?这没有道理。这一切都让人感觉倒退。数组值如何进入 ages.some(checkAdult)
调用?点之前的关键字是否变成了我想象中应该在 checkAdult
之后括号中的参数?
为什么它不去 some(checkAdult(ages))
?
为什么要将它附加到带点的内容的末尾?
var ages = [3, 10, 18, 20];
function checkAdult(age) { // THIS LINE HERE, how does it link to the array???
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.some(checkAdult);
}
<p>Click the button to check if any of the elements in the array has a value of 18 or more.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
通常(但不总是)user-supplied 函数由 higher-order 函数调用。
在下面的示例中,some
对 t
的每个元素调用 f
,直到找到第一个真实结果。否则返回错误结果。
const some = (f, t) =>
t.length === 0
? false
: Boolean(f(t[0])) // f gets called by some
|| some(f, t.slice(1))
console.log(some(v => v > 30, [ 10, 20, 30, 40 ]))
// true
console.log(some(v => v > 99, [ 10, 20, 30, 40 ]))
// false
或同一程序的迭代版本 -
function some (f, t)
{ for (const v of t)
if (Boolean(f(v)))
return true
return false
}
console.log(some(v => v > 30, [ 10, 20, 30, 40 ]))
// true
console.log(some(v => v > 99, [ 10, 20, 30, 40 ]))
// false