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

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

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

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


当前回答

我知道我迟到了,但我只是无法相信+运算符的有用性除了“将任何东西转换为数字”之外没有被提及。也许这就是隐藏得有多好?

// Quick hex to dec conversion:
+"0xFF";              // -> 255

// Get a timestamp for now, the equivalent of `new Date().getTime()`:
+new Date();

// Safer parsing than parseFloat()/parseInt()
parseInt("1,000");    // -> 1, not 1000
+"1,000";             // -> NaN, much better for testing user input
parseInt("010");      // -> 8, because of the octal literal prefix
+"010";               // -> 10, `Number()` doesn't parse octal literals 

// A use case for this would be rare, but still useful in cases
// for shortening something like if (someVar === null) someVar = 0;
+null;                // -> 0;

// Boolean to integer
+true;                // -> 1;
+false;               // -> 0;

// Other useful tidbits:
+"1e10";              // -> 10000000000
+"1e-4";              // -> 0.0001
+"-12";               // -> -12

当然,你也可以用Number()来代替,但是+运算符要漂亮得多!

您还可以通过重写原型的valueOf()方法为对象定义一个数值返回值。在该对象上执行的任何数字转换都不会导致NaN,而是valueOf()方法的返回值:

var rnd = {
    "valueOf": function () { return Math.floor(Math.random()*1000); }
};
+rnd;               // -> 442;
+rnd;               // -> 727;
+rnd;               // -> 718;

其他回答

所有“隐藏的”特性都在Mozilla wiki上:http://developer.mozilla.org/en/JavaScript。

这里有JavaScript 1.5的核心参考,JavaScript 1.6的新特性,JavaScript 1.7的新特性,以及JavaScript 1.8的新特性。看看所有这些实际工作的例子,是正确的。

函数在JavaScript中是第一类公民:

var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z); };

var sum = function(x,y,z) {
  return x+y+z;
};

alert( passFunAndApply(sum,3,4,5) ); // 12

函数式编程技术可以用来编写优雅的javascript。

特别是,函数可以作为参数传递,例如Array.filter()接受回调:

[1, 2, -1].filter(function(element, index, array) { return element > 0 });
// -> [1,2]

你也可以声明一个“private”函数,它只存在于特定函数的作用域中:

function PrintName() {
    var privateFunction = function() { return "Steve"; };
    return privateFunction();
}

Javascript中的所有对象都实现为哈希表,因此它们的属性可以通过索引器访问,反之亦然。此外,你可以使用for/in操作符枚举所有属性:

var x = {a: 0};
x["a"]; //returns 0

x["b"] = 1;
x.b; //returns 1

for (p in x) document.write(p+";"); //writes "a;b;"

下面是一些有趣的事情:

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类型的实例,它有一个构造函数,该构造函数接受一个包含函数定义的字符串,所以你可以在运行时通过例如连接字符串来定义函数:

//e.g., createAddFunction("a","b") returns function(a,b) { return a+b; }
function createAddFunction(paramName1, paramName2)
 { return new Function( paramName1, paramName2
                       ,"return "+ paramName1 +" + "+ paramName2 +";");
 }

另外,对于用户定义的函数,function . tostring()将函数定义作为文字字符串返回。