简体   繁体   中英

How do I return nothing instead of a blank space in this if statement?

You can see I use "" to make the if statement return nothing in certain cases, but in reality it returns a blank space. I don't want that white space, what could I use instead?

if (n >= 20000 && n < 100000) {
        result = `${tens[Math.floor(n / 10000) - 1]} ${
            Math.floor((n % 10000) / 1000) != 0
                ? num[Math.floor((n % 10000) / 1000)]
                : ""
        } thousand ${n % 1000 != 0 ? number2words(n % 1000) : ""}`;

        return result.trim();
    }

You will have to restructure you code and move the include the space when the condition is truthy.

const tensText = tens[Math.floor(n / 10000) - 1];
const divisible = Math.floor((n % 10000) / 1000);
const hundredsText = divisible != 0 ? ` ${num[divisible]}` : '';
const thousandsText = n % 1000 != 0 ? ` ${number2words(n % 1000)}` : '';

result = `${tensText}${hundredsText} thousand${thousandsText}`;

To return nothing, you'd use return;

However, if one case returns a string, you should probably always return a string for consistency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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