嗨,我自學了MEAN堆棧,並且有一個關於如何減少在我的代碼中檢查數量的問題。如何減少if語句的數量
基本上這個工作由用戶填寫他/她的設置頁面,然後點擊輸入我們然後發送數據到服務器,所以我們可以更新mongo。
我似乎得到這個工作,讓用戶編輯某些領域,而不是所有的唯一方法是確保發送到服務器的數據不等於空,但肯定必須有一個更好的方法然後通過爲每個字段運行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);
}
})
});
};
你從哪裏分配變量?例如,'if(age!= null)','age'從哪裏來? – chridam
你是否考慮過包裝數組中的所有字段,然後在其上運行forEach()方法,這將導致代碼更少,因爲你只有1條語句。 –
會將它添加到現在的隊友 –