简体   繁体   English

有人可以向我解释在调用函数时使用了什么&&吗?

[英]Can somebody explain to me what && does when used with calling a function?

Please explain what this is doing with regards to calling a function and using the && operator. 请解释一下在调用函数和使用&&运算符方面做了些什么。

callback(data && data.length > 1 && JSON.parse(data));

Also, which value actually gets passed to the function? 另外,哪个值实际传递给函数?

I'm guessing callback takes a boolean or an int value. 我猜回调需要一个布尔值或一个int值。

&& is a logical and operator, so it's determining if data is non zero AND data.length is greater than one AND JSON.parse(data) returns non zero, then the expression will result in a 1 or true being passed to callback. &&是逻辑和运算符,因此它确定数据是否为非且data.length大于1 AND JSON.parse(data)返回非零,然后表达式将导致1或true传递给回调。 If any of those parameters are not met, then it will pass 0 or false. 如果不满足任何这些参数,则它将传递0或false。

It is a way to say if data is true(not null) and its length is > 1 then call JSON.parse(data). 这是一种说明数据是否为真(非空)且其长度> 1然后调用JSON.parse(data)的方法。 If first expression is true then only second expression is evaluated and so on. 如果第一个表达式为真,则仅评估第二个表达式,依此类推。 Its equivalent to 它相当于

if(data) 如果(数据)

if(data.length > 1) if(data.length> 1)

callback(JSON.parse(data)); 回调(JSON.parse(数据));

As per me here, only boolean variable will be passed (true/false) 按照我的说法,只传递布尔变量(true / false)

  1. data: checks if data is present or null data:检查数据是否存在或为null
  2. data.length>1 Does the length is more than one. data.length> 1长度是否大于1。 At least two elements should be present in data. 数据中至少应包含两个元素。
  3. return value of JSON.parse(data) It can be either true or false. 返回值JSON.parse(data)它可以是true或false。

It will be much clear, when you come to know what callback accepts exactly. 当您了解回调接受的内容时,将会非常清楚。

&& can be used to evaluate multiple statements at once. &&可用于一次评估多个语句。 && can be thought of as "and". &&可以被认为是“和”。

So, true && false; 所以,真的&& false; evaluates to false. 评估为假。

In JavaScript, && returns the first operand if the first operand is falsy. 在JavaScript中,如果第一个操作数是假的,则&&返回第一个操作数。 If the first operand is truthy, it returns the second operand. 如果第一个操作数是真实的,则返回第二个操作数。

&& is the short-circuiting logical " AND " operator. &&是短路逻辑“ AND ”运算符。 Short-circuiting means that the next component of the expression will be evaluated only if the previous resolves to true. 短路意味着仅当前一个解析为true时才会评估表达式的下一个组成部分。 So, data.length > 1 will not be evaluated unless data is true, and JSON.parse(data) will not be evaluated unless data.length resolves to true. 因此,除非data为true,否则不会计算data.length > 1 ,除非data.length解析为true,否则不会计算JSON.parse(data)

In the end, a boolean value is passed to the method callback() - true if all three components are true: 最后,一个布尔值被传递给该方法callback() - true如果所有三个组件都为真:

  • data
  • data.length > 1
  • JSON.parse(data))

...and false otherwise. ......否则就是false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM