当我从前端发出 GET 请求时,我将几个查询参数应用于 URL,如下所示:
let response = await axios.get('/products?searchQuery=' + this.searchQuery + '&categoryId=' + this.categoryId + '&model=' + this.model + '&page=' + this.currentPage)
问题是,当我在后端 console.log(typeof searchQuery)
时,它说 searchQuery 是一个 string
类型,其值未定义,而不是是未定义
类型。因此,这个 if 语句失败:
if (searchQuery !== undefined) {
}
所以我想知道是否可以将值为“undefined”的字符串转换为实际的未定义数据类型。
最佳答案
不要这样做。严重地。 不要。做。这个。你从Mr. Null的案例中没有学到什么吗? ?
如果前端未定义某个参数,请从请求中完全忽略该参数。
const usp = new URLSearchParams;
const setIfSet = (usp, key, value) => {
if (value == void 0) return;
usp.set(key, value);
};
setIfSet(usp, 'searchQuery', this.searchQuery);
setIfSet(usp, 'categoryId', this.categoryId);
setIfSet(usp, 'model', this.model);
setIfSet(usp, 'page', this.currentPage);
const response = await axios.get('/products?' + usp)
这样,您将在后端实际上得到它的未定义,并且您将不必执行这种愚蠢的解决方法。
如果 Undefine 先生访问您的页面,他将非常感激。
关于javascript - 我可以将值为 'undefined' 的字符串转换为实际的未定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66877936/