你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
当前回答
未定义就是未定义。所以你可以这样做:
if (obj.field === undefined) /* ... */
其他回答
你可以在任何对象上执行一个对象的方法,不管它是否有这个方法。当然,它可能并不总是有效(如果方法假设对象具有它没有的东西),但它可能非常有用。例如:
function(){
arguments.push('foo') // This errors, arguments is not a proper array and has no push method
Array.prototype.push.apply(arguments, ['foo']) // Works!
}
函数在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();
}
let.
与var缺乏块作用域对应的是let,在JavaScript 1.7中引入。
The let statement provides a way to associate values with variables within the scope of a block, without affecting the values of like-named variables outside the block. The let expression lets you establish variables scoped only to a single expression. The let definition defines variables whose scope is constrained to the block in which they're defined. This syntax is very much like the syntax used for var. You can also use let to establish variables that exist only within the context of a for loop.
function varTest() {
var x = 31;
if (true) {
var x = 71; // same variable!
alert(x); // 71
}
alert(x); // 71
}
function letTest() {
let x = 31;
if (true) {
let x = 71; // different variable
alert(x); // 71
}
alert(x); // 31
}
截至2008年,FireFox 2.0+和Safari 3.x支持JavaScript 1.7。
我可以引用道格拉斯·克罗克福德这本好书的大部分内容 JavaScript:好的部分。
但我只给你一个,总是使用===和!==而不是==和!=
alert('' == '0'); //false
alert(0 == ''); // true
alert(0 =='0'); // true
==是不可传递的。如果你使用===,它会给出false for 所有这些陈述都符合预期。
当使用console.log()用于Firebug时,防止在Internet Explorer中测试时出现恼人的错误:
function log(message) {
(console || { log: function(s) { alert(s); }).log(message);
}