我想创建基于条件的变量,但即使是简单的代码我也不能得到新的变量这是我的代码
exports.productPatch = (req, res, next) => {
const id = req.params.productId;
const image = req.body.productImage;
if(image){
const newImage = image;
}else{
const newImage = "1598173461682-636126917.jpg";
}
console.log(newImage);
}
但当我调用newImage时,没有定义响应
您不能重新分配和重新声明用const
声明的变量(见此)。对于您的代码,您可以使用let
,然后根据条件重新分配它。
exports.productPatch = (req, res, next) => {
const id = req.params.productId;
const image = req.body.productImage;
let newImage;
if(image){
newImage = image;
}else{
newImage = "1598173461682-636126917.jpg";
}
console.log(newImage);
}
试试这个
const newImage = (image) ? image : "1598173461682-636126917.jpg"
如果这给出了未定义,请检查您的请求主体是否真的发送了ProductImage。
请检查以下链接中的常量
作用域
https://developer.mozilla.org/en-us/docs/web/javascript/reference/statements/const
常量的值不能通过重新分配来更改,也不能重新声明。
使用let
而不是const
,如下所示作为@divin answer
let newImage = (image) ? image : "1598173461682-636126917.jpg"