Maybe you're curious about what went awry with the loop:
for (i = 0; i < arguments.length; i++){
logicalAnd = arguments[i] && arguments[i+1];
}
- This loop calculates the
&&
of the last two items it comes across. Ideally, it should combine the last two elements of the array, which is not what you actually need.
- Furthermore, at the end of the loop
i=arguments.length-1
, it checks the last element of the array, and i+1
refers to the element "after" the last one, which is undefined
. In terms of logical relationships, this is considered false
, but &&
outputs the value itself in such scenarios, resulting in the function always returning undefined
(this detail could have been mentioned in the question).
Documentation
expr1 && expr2
: If expr1
can be converted to true
, returns expr2
; otherwise, returns expr1
.
arr=[true];
console.log("your case:",arr[0] && arr[1]);
console.log("1 && 2:", 1 && 2);
A better approach would be to use
logicalAnd
as an accumulator that stores the result of combining all previous elements using
&&
. You can optimize by considering that if any partial
&&
calculation results in
false</code, the final output will also be false. Therefore, the loop can terminate early:</p>
<p><div>
<div>
<pre class="lang-js"><code>function andMultipleExpr(){
let logicalAnd = arguments[0] || false;
for (let i = 1; i < arguments.length && logicalAnd; i++){
logicalAnd = logicalAnd && arguments[i];
}
return logicalAnd;
}
console.log("():",andMultipleExpr());
console.log("(false):",andMultipleExpr(false));
console.log("(true):",andMultipleExpr(true));
console.log("(true,true):",andMultipleExpr(true,true));
console.log("(true, true, false, false):",andMultipleExpr(true, true, false, false));