简体   繁体   English

引用Javascript IF语句中的原始条件值

[英]Reference to Originating Conditional Value within a Javascript IF Statement

I often find that I write IF statements which immediately reference the value of the conditional statement. 我经常发现我写的IF语句立即引用了条件语句的值。 For example, let's say I need to check to see if a string matches a pattern: 例如,假设我需要检查字符串是否与模式匹配:

if (mystring.match(/mypattern/) {
    var mymatch = mystring.match(/mypattern/)[1];
    ...
};

I suspect that what I'm looking for doesn't exist, but I've wondered whether you can reference the conditional statement's value within the if block, the way you can reference "arguments" within a function. 我怀疑我要查找的内容不存在,但是我想知道是否可以在if块内引用条件语句的值,即在函数内引用“参数”的方式。 In many cases, of course, I can rewrite it like this: 当然,在很多情况下,我可以这样重写它:

var mymatch = mystring.match(/mypattern/)[1];
if (mymatch) { ... };

But that's often not possible if there's a series of methods called. 但是,如果调用了一系列方法,通常是不可能的。 For example: 例如:

var mymatch = $('.myclass')[0].text().match(/mypattern/)[1];

... that would throw an exception if there were no item [0] on which to call .text(). ...如果没有要调用.text()的项目[0],则将引发异常。 Is there some convenient shorthand I'm missing out on? 我错过了一些方便的速记吗? Or a better way to organize things? 还是组织事物的更​​好方法? Just curious, really — I'll go on living if the answer is no. 真的,只是好奇-如果答案是否定的,我会继续生活。

In cases where relevant you can use the fact that the assignment operator returns a value in JavaScript, so for instance you can write things like: 在相关的情况下,您可以使用赋值运算符在JavaScript中返回值的事实,例如,您可以编写以下内容:

if (assignedTest = testedValue) {
   //value of assignedTest is now available 
   //and conditional will only be executed if true

This could be used if the RHS was compatible or properly set-up but it's also a huge readability concern since it's very easy to confuse the assignment = with comparison == / === . 如果RHS是兼容的或正确设置的,则可以使用此方法, 但是这也是一个很大的可读性问题,因为很容易将赋值=与比较== / ===混淆。

If you were particularly motivated to pursue this you could extract this type of functionality into a function that would behave in a reliable way: such as assigning the result of a closure to a named variable, and you could further tune the behavior to do other things (such as optionally evaluating to a different value within the test). 如果您特别有动机进行此操作,则可以将这种类型的功能提取到可以可靠运行的函数中:例如将闭包的结果分配给命名变量,然后可以进一步调整行为以执行其他操作(例如,可以选择在测试中评估为其他值)。 Ultimately it would primarily be making a simple structure more complex though. 最终,它将最终使一个简单的结构变得更加复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM