简体   繁体   English

为什么这个三元运算符不起作用? (更多下文)

[英]Why this ternary operator not working? (more below)

I have a function, which works fine with if/else, but not with ternary.我有一个 function,它适用于 if/else,但不适用于三元。 Anyone knows the reason?有人知道原因吗? Also, if anyone could tell me a way the make it look nicer I'd really appreciate it.另外,如果有人能告诉我一种让它看起来更好的方法,我会非常感激。

function print(){
    for (const book of myLibrary){
        let cover = document.createElement('div')
        cover.textContent =`title: ${book.title} 
                            author: ${book.author}
                            pages: ${book.pages}` 
        
        // this line: (book.finished) ? cover.classList.add('bookStyle') : cover.classList.add('bookStyle2');
        
        if (book.finished){
            cover.classList.add('bookStyle')
        }
        else{
            cover.classList.add('bookStyle2')
        }

        books.appendChild(cover)
    }
}

Ternaries are great when they are used to return values, not perform or invoke actions.三元组在用于返回值而不是执行或调用操作时非常有用。

Here is how I would improve your ternary.以下是我将如何改进您的三元组。

// Old
this line: (book.finished) ? cover.classList.add('bookStyle') : cover.classList.add('bookStyle2');
// Prefered
cover.classList.add(book.finished ? 'bookStyle' : 'bookStyle2');

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

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