如何减少if语句的数量

how to reduce amount of if statements

本文关键字:语句 何减少 if      更新时间:2023-09-26

嗨,我正在自学MEAN堆栈,有一个关于如何减少代码中if检查数量的问题。

基本上,这是由用户填写他/她的设置页面,然后点击输入,然后将数据发送到服务器,这样我们就可以更新mongo。

我似乎唯一能让用户编辑某些字段(而不是所有字段)的方法是确保发送到服务器的数据不等于null,但肯定有更好的方法,那就是为每个字段运行if语句。

有问题的代码是这个

        //user.username = req.body.username;
    if ( age != null) {
        user.age = age;
    }
    if ( bio != null) {
        user.bio = bio;
    }
    if ( location != null) {
        user.location = location;
    }
    if ( team != null) {
        user.team = team;
    }
    if ( tags != null) {
        user.tags = tags;
    }
    if ( email != null) {
        user.email = email;
    }

客户端代码

    $scope.savesettings = function(provider){
    var theUser = JSON.parse(localStorage.getItem("User-Data"));
    var user = theUser["_id"];
    var request = {};
    var request = {
        user: user,
        username: $scope.settings_username,
        email: $scope.settings_email,
        age: $scope.settings_age,
        location: $scope.settings_location,
        team: $scope.settings_team,
        bio:$scope.settings_bio,
        profilebanner: $scope.settings_profilebanner,
        avatar: $scope.settings_avatar
    };
    console.log(request);
    //send to server
    $http.put('api/social/updatesettings', request).success(function(response){
        alertify.success("Your settings have been successfully saved.");
            localStorage.clear();
            localStorage.setItem('User-Data', JSON.stringify(response));

    }).error(function(error){
        alertify.error("Hmmm an issue has occured.");
     });

};

服务器代码

var User = require('../../datasets/userModel');

module.exports.updatesettings=函数(req,res){

    var age = req.body.age;
    var bio = req.body.bio;
    var location = req.body.location;
    var team = req.body.team;
    var tags = req.body.tags;
    var email = req.body.email;
    var profilebanner = req.body.profilebanner;
    var avatar = req.body.avatar;
User.findOne({_id: req.body.user}, function (err, user){

    //user.username = req.body.username;
    if ( age != null) {
        user.age = age;
    }
    if ( bio != null) {
        user.bio = bio;
    }
    if ( location != null) {
        user.location = location;
    }
    if ( team != null) {
        user.team = team;
    }
    if ( tags != null) {
        user.tags = tags;
    }
    if ( email != null) {
        user.email = email;
    }
    user.save(function(err){
        if (err){
            console.log(err);
            res.status(500).send();
            //res.json(user);
        } else {
            console.log("success");
             res.json(user);
        }
    })
});

};

考虑使用Object.assign。它合并两个或多个对象,后一个对象优先。以下假设data是一个包含agebio等的对象,而user是。。。您的user对象。

var results = Object.assign({}, user, data);

对此有polyfill,如果您碰巧使用jQuery,$.extend通常会做同样的工作。

您可以将所有属性添加到用户对象中。

var user = {
   age: age,
   bio: bio,
   location: location
}

然后删除空值的键。

for (var key in user) {
   if (user[key] === null) {
      delete user[key];
   }
}

一个函数怎么样?您可以将变量数组传递到该函数中,并使用some查看其中是否有null

function isComplete(args) {
  return !args.some(function(el) {
    return el === null;
  });
}
var age = null;
var bio = 'Something';
var location = null;
isComplete([age, bio, location]); // false

if不是问题所在。问题是,您向用户显示了他们不应该看到的字段,所以问题出在表示层。

修复那个系列的if就像在地毯下扫灰尘一样,你似乎想要为你的用户提供角色,所以在你的代码中让它变得清晰易懂。

你可以用服务器端生成的HTML来解决这个问题,比如这样(语法可能有问题,但我希望你能理解):

<% if (user.canSetTeam()) { %>
  <input type="text" name="team" />
<% } %>

因此,在HTML中,您将拥有正确的字段。

看看http://expressjs.com/en/guide/using-template-engines.html