Ala*_*ect 3 javascript typescript tslint
我刚刚编写了下面的循环,效果很好:
let position = 0;
// tslint:disable-next-line:no-conditional-assignment
while ((position = source.indexOf('something interesting', position)) > 0) {
// do something interesting with something interesting
position += 1;
}
Run Code Online (Sandbox Code Playgroud)
但是请注意,我必须添加tslint例外。显然,有人决定不希望在while条件内包含赋值语句
。但是,对于这种特殊情况,这是我所知道的最直接的代码模式。
如果这不是“允许的”(或者我应该说“受挫的”),那么推动这一工作的人们认为正确的代码模式是什么?
这使得难以确定代码的意图。使用赋值作为表达式是不寻常的 -如果在条件中看到赋值,您如何确定打算使用赋值的代码的编写者,或者它可能是拼写错误?如果代码编写者打算比较该值怎么办?例如
while ((position = source.indexOf('something interesting', position)) > 0) {
Run Code Online (Sandbox Code Playgroud)
与
while ((position == source.indexOf('something interesting', position)) > 0) {
Run Code Online (Sandbox Code Playgroud)
那两个是非常不同的。(在这种特殊情况下,Typescript会警告您,将布尔值和数字进行比较可能是一个错误,但这在Javascript中不会发生,在其他情况下也不会发生。)
而不是它的条件,转让外内分配,甚至更好,对于上面的代码,你可以很可能使用正则表达式(尽管它很难说肯定不知道的内容// do something interesting with something interesting)。
不幸的是,它看起来像是重复的,但是另一种方法是
let position = 0;
const getPos = () => {
position = source.indexOf('something interesting', position);
};
getPos();
while (position > 0) {
// do something interesting with something interesting
getPos();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |