简体   繁体   English

为什么for ... of语句中的三元运算符不起作用?

[英]Why is the ternary operator in the for…of statement not working?

I am not sure why the ternary operator is not working in this example. 我不确定为什么在此示例中三元运算符不起作用。 I have seen it used in similar ways before but I can not get it to work properly in this test. 我以前曾以类似的方式使用过它,但是在此测试中我无法使其正常工作。 Any help would be greatly appreciated! 任何帮助将不胜感激!

const numbers = [1, 2, 3, 4, 5];

console.log(includes(numbers, 4));
//This works fine
function includes(array, searchElement) {
    for (let element of array)
        if (element === searchElement)
            return true;
    return false;
}

This solution works fine but when I try to use the ternary operator I always get false. 这种解决方案效果很好,但是当我尝试使用三元运算符时,我总是会得到错误的结果。

console.log(includes2(numbers, 4));

function includes2(array, searchElement) {
    for (let element of array) {
        return (element === searchElement ? true : false);
    }
}

Lets add blocks and convert the conditional operator back to if : 让我们添加块并将条件运算符转换回if

First example: 第一个例子:

function includes(array, searchElement) {
    for (let element of array) {
        if (element === searchElement) {
            return true;
        }
    }
    return false;
}

Second example: 第二个例子:

function includes2(array, searchElement) {
    for (let element of array) {
        // return (element === searchElement ? true : false);
        if (element === searchElement) {
           return true;
        }
        return false;
    }
}

Note the position of the return false; 注意return false;的位置return false; statement. 声明。 In the first case you return after the loop. 在第一种情况下,循环后返回。 In the second case you return inside the loop, ie the function will always terminate in the first iteration of the loop. 在第二种情况下,您将在循环内返回,即该函数将始终在循环的第一次迭代中终止。

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

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