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

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

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

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


当前回答

也许对某些人来说有点明显…

安装Firebug并使用console.log("hello")。这比使用随机alert();好多了,我记得几年前我经常这样做。

其他回答

“JavaScript中的扩展方法”通过prototype属性。

Array.prototype.contains = function(value) {  
    for (var i = 0; i < this.length; i++) {  
        if (this[i] == value) return true;  
    }  
    return false;  
}

这将为所有Array对象添加一个contains方法。您可以使用以下语法调用此方法

var stringArray = ["foo", "bar", "foobar"];
stringArray.contains("foobar");

也许其中一个不太为人所知:

arguments. called .caller + Function#toString()

function called(){
    alert("Go called by:\n"+arguments.callee.caller.toString());
}

function iDoTheCall(){
    called();
}

iDoTheCall();

打印出idocall的源代码—— 已弃用,但有时在警报是您唯一的选择时可能有用....

要将浮点数转换为整数,您可以使用以下神秘的技巧之一(请不要这样做):

3.14 >> 0(通过2.9999999999999999 >> .5?) 3.14 | 0(通过JavaScript中将浮点数转换为整数的最佳方法是什么?) 3.14 & -1 3.14 ^ 0 ~ ~ 3.14

基本上,对浮点数应用任何二进制操作都不会改变最终值(即恒等函数),最终会将浮点数转换为整数。

JavaScript中最快的循环是while(i——)循环。在所有浏览器中。 所以如果循环元素的处理顺序不是那么重要,你应该使用while(i——)形式:

var names = new Array(1024), i = names.length;
while(i--)
  names[i] = "John" + i;

此外,如果你必须继续使用for()循环,请记住始终缓存.length属性:

var birds = new Array(1024); 
for(var i = 0, j = birds.length; i < j; i++)
  birds[i].fly();

要连接大字符串使用数组(它更快):

var largeString = new Array(1024), i = largeString.length;
while(i--) {
  // It's faster than for() loop with largeString.push(), obviously :)
  largeString[i] = i.toString(16);
}

largeString = largeString.join("");

它比循环中的largeString += "something"快得多。

JavaScript使用Date()的方式让我很兴奋!

function isLeapYear(year) {
    return (new Date(year, 1, 29, 0, 0).getMonth() != 2);
}

这是真正的“隐藏特性”。

编辑:删除了评论中建议的“?”条件。 是:……new Date(year, 1,29,0,0).getMonth() != 2 ?真:假…… 详情请看评论。