gpt4 book ai didi

javascript - 使用带有 javascript 的逻辑运算符压缩 if/else if 语句

转载 作者:行者123 更新时间:2023-11-29 21:05:15 24 4
gpt4 key购买 nike

我正在学习 AngularJS,试图制作一个简单的计算器,并且我正在尝试压缩这个 if/else if 语句到 1-2 行,使用 Javascript 逻辑运算符(&&||!)

鉴于此示例,我该如何减少它?(不懂$scope的可以无视,基本就是一个 View 。所以当有人点击9时,计算器会在答题屏上显示9)

$scope.setOperand = function (operandEntered) {

if ($scope.leftOperand === null) {
$scope.leftOperand = operandEntered;
}
else if ($scope.operator === null) {
$scope.leftOperand = $scope.leftOperand + operandEntered;
}
else if ($scope.rightOperand === null) {
$scope.rightOperand = operandEntered;
}
else if ($scope.answer === null) {
$scope.rightOperand = $scope.rightOperand + operandEntered;
}
};

最佳答案

一个人总是可以(尝试)变得聪明,但是当代码变得更长并且不再更可重用时,抽象并不总能带来返回。 KISS .

如果你愿意,我会选择

function addTo(property, x, operand) { // "x" for lack of a more meaningful name
const shouldAdd = $scope[property] === null || $scope[x] === null;
if (shouldAdd)
$scope[property] += operand; // assuming "operand" is a number
// or $scope[property] = ($scope[property] || "") + operand; // when it's a string
return shouldAdd;
}
$scope.setOperand = function (operandEntered) {
addTo("leftOperand", "operator", operandEntered) || addTo("rightOperand", "answer", operandEntered);
};

如果你更关心简洁而不是可读性,你甚至可以将帮助程序缩短为

function addTo(property, x, operand) {
return ($scope[property] === null || $scope[x] === null) && (($scope[property] += operand), true);
}

关于javascript - 使用带有 javascript 的逻辑运算符压缩 if/else if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44424336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com