简体   繁体   English

为什么不能使用“ !! document.getElementsByClassName && function(){return document.getElementsByClassName(obj)}”简化代码

[英]Why can't use “ !!document.getElementsByClassName && function(){return document.getElementsByClassName(obj)}” for simplifing codes

when I want to check whether getElementsByClassName exists for Explorer. 当我想检查getElementsByClassName是否存在资源管理器时。 I use under code and it's working well. 我在代码下使用,并且运行良好。

 function getClass(obj) { if (document.getElementsByClassName) { return document.getElementsByClassName(obj) } }//work well 

for simplify my codes, I change codes and work well also: 为了简化我的代码,我更改了代码,并且效果也不错:

 function getClass(obj) { if (document.getElementsByClassName) return document.getElementsByClassName(obj); }//work well 
But when I write this , it gives some error 但是当我写这个的时候,它给了一些错误

 function getClass(obj) { !!document.getElementsByClassName && ( return document.getElementsByClassName(obj)); }//work badly 

There is a error within Chrome.Error message is "Uncaught SyntaxError: Unexpected token return". Chrome内发生错误。错误消息为“未捕获的SyntaxError:意外的令牌返回”。 for cure this error,I change my codes ,see under: 为解决此错误,我更改了代码,请参见以下内容:

 function getClass(obj) { !!document.getElementsByClassName && function() { return document.getElementsByClassName(obj) }; } 

BUT,when I use getClass() ,there console show "undefined". 但是,当我使用getClass()时 ,控制台显示“ undefined”。

for description above, 对于上面的描述,

  1. I don't know why "&&" used so hard? 我不知道为什么“ &&”这么用?
  2. I want to know is there has some simplify code? 我想知道是否有一些简化代码?

The problem with this one: 这个问题:

function getClass(obj) {
    !!document.getElementsByClassName && ( return document.getElementsByClassName(obj) );
}//work badly

You can't use return as part of a logic expression. 您不能将return用作逻辑表达式的一部分。

The problem with this one: 这个问题:

function getClass(obj) {
    !!document.getElementsByClassName && function() {
        return document.getElementsByClassName(obj)
    };
}

You don't actually return anything, you just create an anonymous function that is not assigned to anything, so the default undefined is always returned. 您实际上并没有return任何内容,只是创建了一个未分配任何内容的匿名函数,因此始终返回默认的undefined

You could do something like this by putting return before the logic conditions. 您可以通过将return放在逻辑条件之前来执行类似的操作。

function getClass(obj) {
    return !!document.getElementsByClassName && document.getElementsByClassName(obj);
}

Honestly though, these short circuit tricks really aren't simpler, and I would recommend just using option 1 or perhaps the ternary operator. 坦白说,这些短路技巧实际上并不简单,我建议仅使用选项1或三元运算符。

function getClass(obj) {
    return document.getElementsByClassName ?
        document.getElementsByClassName(obj) :
        null;
}

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

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