你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
当前回答
大型循环在while-condition和反向条件下更快——也就是说,如果循环的顺序对您无关紧要的话。在我大约50%的代码中,它通常不存在。
即。
var i, len = 100000;
for (var i = 0; i < len; i++) {
// do stuff
}
比:
i = len;
while (i--) {
// do stuff
}
其他回答
正如Marius已经指出的,可以在函数中使用公共静态变量。
我通常使用它们来创建只执行一次的函数,或者缓存一些复杂的计算结果。
下面是我以前的“单例”方法的例子:
var singleton = function(){
if (typeof arguments.callee.__instance__ == 'undefined') {
arguments.callee.__instance__ = new function(){
//this creates a random private variable.
//this could be a complicated calculation or DOM traversing that takes long
//or anything that needs to be "cached"
var rnd = Math.random();
//just a "public" function showing the private variable value
this.smth = function(){ alert('it is an object with a rand num=' + rnd); };
};
}
return arguments.callee.__instance__;
};
var a = new singleton;
var b = new singleton;
a.smth();
b.smth();
如您所见,在这两种情况下构造函数都只运行一次。
For example, I used this approach back in 2004 when I had to create a modal dialog box with a gray background that covered the whole page (something like Lightbox). Internet Explorer 5.5 and 6 have the highest stacking context for <select> or <iframe> elements due to their "windowed" nature; so if the page contained select elements, the only way to cover them was to create an iframe and position it "on top" of the page. So the whole script was quite complex and a little bit slow (it used filter: expressions to set opacity for the covering iframe). The "shim" script had only one ".show()" method, which created the shim only once and cached it in the static variable :)
您可以将“任何具有整数属性和长度属性的*对象转换为适当的数组,从而赋予它所有数组方法,如push、pop、splice、map、filter、reduce等。
Array.prototype.slice.call({"0":"foo", "1":"bar", 2:"baz", "length":3 })
//返回["foo", "bar", "baz"]
这适用于jQuery对象,html集合和来自其他框架的数组对象(作为整个数组类型的一种可能的解决方案)。我说,如果它有一个长度属性,你可以把它变成一个数组,这没有关系。有很多非数组对象都有length属性,在arguments对象之外。
当使用console.log()用于Firebug时,防止在Internet Explorer中测试时出现恼人的错误:
function log(message) {
(console || { log: function(s) { alert(s); }).log(message);
}
如果您在google上搜索关于给定主题的像样的JavaScript参考,在查询中包含“mdc”关键字,那么您的第一个结果将来自Mozilla Developer Center。我没有随身携带任何离线参考资料或书籍。我总是使用“mdc”关键字来直接找到我要找的东西。例如:
谷歌:javascript数组排序mdc (在大多数情况下,你可以省略“javascript”)
更新:Mozilla开发者中心已重命名为Mozilla开发者网络。“mdc”关键字技巧仍然有效,但很快我们可能不得不开始使用“mdn”来代替。
Function.toString()(隐性):
function x() {
alert("Hello World");
}
eval ("x = " + (x + "").replace(
'Hello World',
'STACK OVERFLOW BWAHAHA"); x("'));
x();