有人可以帮助我解释此JavaScript代码中的IF语句吗?
function filterArray(array, callback) {
const newArray = [];
for (let i = 0; i < array.length; i += 1) {
if (callback(array[i])) newArray.push(array[i]);
}
return newArray;
}
我对语法感到困惑。通常,到目前为止,我所看到的是
if (condition) {
// code to be executed
}
条件是一些布尔语句,如果条件= true,将运行显示的代码。
但是,在此IF语句中,没有布尔值,在Conditonal语句之后也没有执行代码。我不知道这意味着什么。在此先感谢您对其进行任何帮助。
function filterArray(array, callback) {
const newArray = [];
for (let i = 0; i < array.length; i += 1) {
if (callback(array[i])) newArray.push(array[i]);
}
return newArray;
}
I'm confused by the syntax. Typically what I've seen so far is
if (condition) {
// code to be executed
}
where condition is some boolean statement which will run the code shown if condition = true.
But, in this if statement, there is no boolean, nor is there code to be executed after the conditonal statement. I have no clue what it means. Thanks in advance for any help interpeting it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(callback(array [i]))
此部分是条件。newarray.push(array [i])
这是满足条件时发生的情况。它看起来很近。做同样的事情。
(callback(array[i]))
this part is the condition.newArray.push(array[i])
this is what happens when the condition is met. It just looks so close together.Does same thing.
是一个布尔值,即带有参数
array [i]
的函数回调
返回的值。 (确切地说:根据JavaScript语言规格将返回值解释为真实价值 - 这就是“真实”或“ falsy”的含义。对于开始者,只需假设chardback
确实确实,返回一个布尔值)也正在执行代码:条件之后的第一个语句。
这只是一个符号速记。详细的等效代码将是:
There is a boolean, namely the value returned from calling the function
callback
with argumentarray[i]
. (To be precise: The interpretation of the returned value as a truth value according to the JavaScript language specs - this is what is meant by 'truthy' or 'falsy'. For starters just assume thatcallback
does indeed return a boolean value)There also is code being executed: The first statement after the condition.
This is just a notational shorthand. The verbose equivalent code would be:
if(callback(array [i]))newarray.push(array [i]);
仅表示callback
是一个函数,被调用,返回值为预期(可能是任何价值,不仅是布尔值)。然后,如果返回为真实,则语句newarray.push(array [i]);
被执行。(单行
如果(EXP)语句;
可以像这样写,但有时可能会隐藏错误,因此某些Linter倾向于始终将其更改为回调的函数通常是作为参数传递的功能(正如您在这里看到的那样),然后被调用。
if (callback(array[i])) newArray.push(array[i]);
simply means thatcallback
is a function, that gets called and a return value is expected (could be any value, not only boolean). Then, if the return is truthy, the statementnewArray.push(array[i]);
gets executed.(A single line
if (exp) statement;
can be written like this, but may sometimes hide bugs, so some linters prefer to always change it toCallbacks are typically functions that get passed in as an argument (exactly as you see here) that then may get called.
如果您的病情不起作用,请尝试使用if否则循环。如果您的语句不是您期望显示错误消息,否则按阵列[i];
If your condition isn't working try to use a if else loop. If your statement isn't what you expect show an error message, else push array[i];