简体   繁体   中英

Why does the || operator not work in JavaScript?

I am trying to paginate using Node.js and Express and I want if the slug <= 0 , slug = 1 .

new(req, res, next) {
        let perPage = 16;
        //let page = req.params.page <= 0 ? 1: req.params.page; //This work
        let page = req.params.page || 1; //BUT this NOT work, please explain for me

        Product 
            .find()
            .skip((perPage * (page - 1)))
            .limit(perPage)
            .exec((err, products) => {
                    Product.countDocuments((err, count) => { 
                        if (err) return next(err);
                        res.render('product/index_product', {
                            products, 
                            current: page, 
                            pages: Math.ceil(count / perPage) 
                        });
                    });
            });
    }

I used the || operator to solve it but it does not work, I don't know why.

In the case of the page being 0, query string parameters are parsed as strings .

req.params.page <= 0? 1 req.params.page <= 0? 1 works because '0' is, lexiographically, indeed <= 0 (when then 0 on the right gets implicitly coerced to '0' ).

 console.log('0' <= 0);

But '0' is not falsey, so

let page = req.params.page || 1;

is

let page = '0' || 1;
let page = '0'

Convert the page to a number first.

const paramPage = Number(req.params.page);
const page = paramPage || 1;

In the case of the page being negative , let page = req.params.page || 1 let page = req.params.page || 1 wouldn't make sense anyway - negative numbers are truthy too. If that's a possibility in your code, your original approach of

const page = req.params.page <= 0 ? 1:

is the best one there is.

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