这是一个涉及多个三元运算符的过于复杂的表达式.
我认为它应该被简化.
三元运算符的行为类似于if
,但它是一个根据第一个操作数返回两个选项中的一个值的表达式.
例如:
operand ? valueIfTrue : valueIfFalse
是一个三元表达式,如果operand
为"真",则返回valueIfTrue
;如果operand
为"假",则返回valueIfFalse
.
你可以用任何表达式来代替valueIfTrue
和valueIfFalse
,这样你就可以得到非常复杂的表达式,有时甚至是不必要的复杂.
As an example of making expressions complicated, let's consider: 例如: operand ? valueIfTrue : valueIfFalse
如果我们随后用另一个三元运算符(例如myOtherOperand ? myOtherIfTrue : myOtherIfFalse
)替换valueIfTrue,则原始表达式变为:
operand ? myOtherOperand ? myOtherIfTrue : myOtherIfFalse: valueIfFalse
个
这不是一种很好的写作方式,可以这样改进,我只是加了一个括号.
operand ? (myOtherOperand ? myOtherIfTrue : myOtherIfFalse) : valueIfFalse
个
可以通过如下格式再次改进它:
operand
? myOtherOperand
? myOtherIfTrue // if both operand and myOtherOperand are true
: myOtherIfFalse // if operand is true and myOtherOperand is false
: valueIfFalse // this will be returned if operand is false
这表明代码格式化对于理解它是必不可少的.但当然,第一步是拥有简单的代码.无论如何,以下是我将如何格式化问题中的代码,以便更容易理解:
function myFunction(t) {
for (var e, r = t.length, n = "", i = 0, s = 0, a = 0; i < r; ) {
(s = t.charCodeAt(i)) < 128
? (n += String.fromCharCode(s), i++)
: s > 191 && s < 224
? (a = t.charCodeAt(i + 1), n += String.fromCharCode((31 & s) << 6 | 63 & a), i += 2)
: (a = t.charCodeAt(i + 1),
e = t.charCodeAt(i + 2),
n += String.fromCharCode((15 & s) << 12 | (63 & a) << 6 | 63 & e),
i += 3); // end of ternary operators
return n;
}
}
现在更清楚了,我们可以看到使用的两个三元运算符内部用逗号分隔的语句.逗号用于执行同一表达式中的多个内容,例如,(n += String.fromCharCode(s), i++)
会增加n
,也会增加i
.在这种情况下,最好是将它们移出三元组,并将其移到正常的if
语句中,如下所示:
function myFunction(t) {
for (var e, r = t.length, n = "", i = 0, s = 0, a = 0; i < r;) {
const firstCheck = (s = t.charCodeAt(i)) < 128;
const secondCheck = s > 191 && s < 224;
if (firstCheck) {
n += String.fromCharCode(s);
i++;
} else if (secondCheck) {
// This is originally: (a = t.charCodeAt(i + 1), n += String.fromCharCode((31 & s) << 6 | 63 & a), i += 2);
a = t.charCodeAt(i + 1);
n += String.fromCharCode((31 & s) << 6 | 63 & a);
i += 2;
} else {
// this is originally:
// (a = t.charCodeAt(i + 1),
// e = t.charCodeAt(i + 2),
// n += String.fromCharCode((15 & s) << 12 | (63 & a) << 6 | 63 & e),
// i += 3);
a = t.charCodeAt(i + 1);
e = t.charCodeAt(i + 2);
n += String.fromCharCode((15 & s) << 12 | (63 & a) << 6 | 63 & e);
i += 3;
}
return n;
}
}
所以基本上把它分解,一步一步地go 理解它,然后你就可以改变它,因为你理解了它.