你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?

在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。

HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性

尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。


当前回答

真实和虚假价值的概念。你不需要做这种事

if(someVar === undefined || someVar === zero) ...

只是做的事:

if (! someVar)。

每个值都有一个对应的布尔表示。

其他回答

存在检查。我经常看到这样的东西

var a = [0, 1, 2];

// code that might clear the array.

if (a.length > 0) {
 // do something
}

例如,你可以这样做:

var a = [0, 1, 2];

// code that might clear the array.

if (a.length) { // if length is not equal to 0, this will be true
 // do something
}

你可以做各种各样的存在性检验,但这只是一个简单的例子

下面是一个关于如何使用默认值的示例。

function (someArgument) {
      someArgument || (someArgument = "This is the deault value");
}

这是我的意见。还有其他鸡块,但就到这里了。

下面是一些有趣的事情:

Comparing NaN with anything (even NaN) is always false, that includes ==, < and >. NaN Stands for Not a Number but if you ask for the type it actually returns a number. Array.sort can take a comparator function and is called by a quicksort-like driver (depends on implementation). Regular expression "constants" can maintain state, like the last thing they matched. Some versions of JavaScript allow you to access $0, $1, $2 members on a regex. null is unlike anything else. It is neither an object, a boolean, a number, a string, nor undefined. It's a bit like an "alternate" undefined. (Note: typeof null == "object") In the outermost context, this yields the otherwise unnameable [Global] object. Declaring a variable with var, instead of just relying on automatic declaration of the variable gives the runtime a real chance of optimizing access to that variable The with construct will destroy such optimzations Variable names can contain Unicode characters. JavaScript regular expressions are not actually regular. They are based on Perl's regexs, and it is possible to construct expressions with lookaheads that take a very, very long time to evaluate. Blocks can be labeled and used as the targets of break. Loops can be labeled and used as the target of continue. Arrays are not sparse. Setting the 1000th element of an otherwise empty array should fill it with undefined. (depends on implementation) if (new Boolean(false)) {...} will execute the {...} block Javascript's regular expression engine's are implementation specific: e.g. it is possible to write "non-portable" regular expressions.

[更新了一点,以回应良好的评论;请参阅评论]

私有方法

对象可以有私有方法。

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

    // A private method only visible from within this constructor
    function calcFullName() {
       return firstName + " " + lastName;    
    }

    // A public method available to everyone
    this.sayHello = function () {
        alert(calcFullName());
    }
}

//Usage:
var person1 = new Person("Bob", "Loblaw");
person1.sayHello();

// This fails since the method is not visible from this scope
alert(person1.calcFullName());

为变量分配默认值

你可以在赋值表达式中使用逻辑运算符||来提供一个默认值:

var a = b || c;

只有当b为false (if为null, false, undefined, 0,空字符串或NaN)时,变量a才会得到c的值,否则a将得到b的值。

这通常在函数中很有用,当你想在没有提供参数的情况下给参数一个默认值:

function example(arg1) {
  arg1 || (arg1 = 'default value');
}

事件处理程序中的IE回退示例:

function onClick(e) {
    e || (e = window.event);
}

以下语言特性已经伴随我们很长时间了,所有JavaScript实现都支持它们,但直到ECMAScript第5版才成为规范的一部分:

调试器语句

§12.15调试器语句描述

这个语句允许你通过以下方式在代码中添加断点:

// ...
debugger;
// ...

如果有调试器存在或处于活动状态,则会导致调试器立即在这一行上中断。

否则,如果调试器不存在或不活动,则此语句没有可观察到的效果。

多行字符串字面值

在§7.8.4字符串字面量中描述

var str = "This is a \
really, really \
long line!";

您必须小心,因为\旁边的字符必须是行结束符,例如,如果在\后面有空格,代码将看起来完全相同,但它将引发SyntaxError。

可以使用[]而不是。

这允许您查找与变量匹配的属性。

obj = {a:"test"};
var propname = "a";
var b = obj[propname];  // "test"

您还可以使用此命令获取/设置名称不是合法标识符的对象属性。

obj["class"] = "test";  // class is a reserved word; obj.class would be illegal.
obj["two words"] = "test2"; // using dot operator not possible with the space.

有些人不知道这一点,最终像这样使用eval(),这是一个非常糟糕的主意:

var propname = "a";
var a = eval("obj." + propname);

这更难阅读,更难发现错误(不能使用jslint),执行速度更慢,并可能导致XSS漏洞。