你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
当前回答
存在检查。我经常看到这样的东西
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");
}
这是我的意见。还有其他鸡块,但就到这里了。
其他回答
函数语句和函数表达式的处理方式不同。
function blarg(a) {return a;} // statement
bleep = function(b) {return b;} //expression
所有函数语句在代码运行之前都会被解析——JavaScript文件底部的函数将在第一个语句中可用。另一方面,它将无法利用某些动态上下文,例如围绕语句—在解析函数时,with还没有执行。
函数表达式在遇到它们的地方内联执行。在此之前它们是不可用的,但它们可以利用动态上下文。
Function.toString()(隐性):
function x() {
alert("Hello World");
}
eval ("x = " + (x + "").replace(
'Hello World',
'STACK OVERFLOW BWAHAHA"); x("'));
x();
在我的脑海中…
功能
参数。Callee指的是承载“arguments”变量的函数,所以它可以用来递归匿名函数:
var recurse = function() {
if (condition) arguments.callee(); //calls recurse() again
}
如果你想做这样的事情,这很有用:
//do something to all array items within an array recursively
myArray.forEach(function(item) {
if (item instanceof Array) item.forEach(arguments.callee)
else {/*...*/}
})
对象
关于对象成员有一个有趣的事情:他们可以有任何字符串作为他们的名字:
//these are normal object members
var obj = {
a : function() {},
b : function() {}
}
//but we can do this too
var rules = {
".layout .widget" : function(element) {},
"a[href]" : function(element) {}
}
/*
this snippet searches the page for elements that
match the CSS selectors and applies the respective function to them:
*/
for (var item in rules) {
var elements = document.querySelectorAll(rules[item]);
for (var e, i = 0; e = elements[i++];) rules[item](e);
}
字符串
字符串。Split可以将正则表达式作为参数:
"hello world with spaces".split(/\s+/g);
//returns an array: ["hello", "world", "with", "spaces"]
字符串。Replace可以将正则表达式作为搜索参数,将函数作为替换参数:
var i = 1;
"foo bar baz ".replace(/\s+/g, function() {return i++});
//returns "foo1bar2baz3"
JavaScript中的时间戳:
// Usual Way
var d = new Date();
timestamp = d.getTime();
// Shorter Way
timestamp = (new Date()).getTime();
// Shortest Way
timestamp = +new Date();
令人惊讶的是,很多人都没有意识到它也是面向对象的。