[英]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
.我正在尝试使用 Node.js 和 Express 进行分页,如果
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 .在页面为 0 的情况下,查询字符串参数被解析为字符串。
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'
). req.params.page <= 0? 1
有效,因为'0'
在字典上确实<= 0
(当右边的0
被隐式强制转换为'0'
时)。
console.log('0' <= 0);
But '0'
is not falsey, so但是
'0'
不是假的,所以
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
在 page 为负数的情况下,
let page = req.params.page || 1
let page = req.params.page || 1
wouldn't make sense anyway - negative numbers are truthy too. let page = req.params.page || 1
无论如何都没有意义 - 负数也是真实的。 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.是最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.