简体   繁体   English

具有三元运算符语法的JavaScript Prime Checker函数

[英]JavaScript Prime Checker Function with Ternary Operator Syntax

How can I refactor the following using the ternary operator syntax instead? 如何使用三元运算符语法重构以下内容?

let divisor = 2;
let isPrime = (num) => {
        if (num % divisor === 0) return false;
        else divisor++;
        return true;
};

console.log(`prime is ${isPrime(83)}`);

You can use conditional operator with comma operator following : at exp2 您可以使用条件运算符逗号操作如下:exp2

 let divisor = 2; let isPrime = num => num % divisor === 0 ? false : (++divisor, true); console.log(`prime is ${isPrime(83)}`); 

You can increment the number and convert it to a Boolean, because numbers that are not 0 will be converted to true 您可以增加数字并将其转换为布尔值,因为非0的数字将转换为true

(num) => num % divisor ? // > 0 == true : 0 == false
    !!(++divisor) // increment and convert to boolean
    : 
    false

 let divisor = 2; const isPrime = (num) => num % divisor ? !!(++divisor) : false; console.log(`prime is ${isPrime(83)}`); 

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

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