我有以下变量:
if(req.body.author === undefined) {
console.log('author undefined');
}
我只想分配定义的值。例如,我可以通过以下方式检查undefined:
undefined
但是如何将其翻译为不分配值?我是否需要事后检查,然后删除属性{{1}}?
答案 0 :(得分:2)
如果在帖子数据中未定义属性,你能不能只使用默认值并将它们设置为null?
//Unsure if you want the default value to have any meaning
//using null would likely achieve what you're asking.
var default_value = null;
const quote = {
author: req.body.author || default_value,
quote: req.body.quote || default_value,
source: req.body.source || default_value,
updatedAt: Date.now(),
};
如果你真的想剥离它们,这里是你可以使用的基本循环。
for (var i in quote) {
if (quote[i] == default_value) {
//Unsure how this works with const... might have to change to var
delete quote[i];
}
}
或者,您可以迭代req.body对象,避免在初始声明后进行验证。
var quote = {};
for (var i in req.body) {
quote[i] = req.body[i];
}
不确定您是否仍想验证req.body对象中的某些值,以便可以添加对它们的检查为null / undefined
var quote = {};
for (var i in req.body) {
//This will only declare the value on the quote object if the value
//is not null or undefined. False could be a value you're after so
//I avoided using the cleaner version of 'if (!req.body[i]) ...'
if (req.body[i] !== null || req.body[i] !== undefined) {
quote[i] = req.body[i];
}
}
你甚至可以把它分解成一个很好的可重用函数(下面的基本实现):
//Obj would be your post data
//bad_values would be an array of values you're not interested in.
function validatePOST (obj, bad_values) {
var data = {};
for (var i in obj) {
//Check the value isn't in the array of bad values
if (bad_values.indexOf(obj[i]) === -1) {
data[i] = obj[i];
}
}
//Return the validated object
return data;
}
现在您可以在所有路线中使用它。
var quote = validatePOST(req.body, [null, undefined]);