你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
你认为每个程序员都应该知道JavaScript的哪些“隐藏特性”?
在看到以下问题的优质答案后,我认为是时候向JavaScript请求它了。
HTML的隐藏特性 CSS的隐藏特性 PHP的隐藏特性 ASP的隐藏特性。网 c#的隐藏特性 Java的隐藏特性 Python的隐藏特性
尽管JavaScript可以说是目前最重要的客户端语言(问问谷歌就知道了),但令人惊讶的是,大多数web开发人员很少意识到它的强大。
当前回答
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。
其他回答
jQuery和JavaScript:
变量名可以包含许多奇数字符。我使用$字符来标识包含jQuery对象的变量:
var $links = $("a");
$links.hide();
jQuery的对象链接模式非常好,但是应用这个模式可能会让人有点困惑。幸运的是JavaScript允许你断行,就像这样:
$("a")
.hide()
.fadeIn()
.fadeOut()
.hide();
一般的JavaScript:
我发现通过使用自执行函数来模拟作用域很有用:
function test()
{
// scope of test()
(function()
{
// scope inside the scope of test()
}());
// scope of test()
}
你可以在左边使用[]来分配局部变量。如果你想从一个函数中返回多个值,而不需要创建一个不必要的数组,这个方法很方便。
function fn(){
var cat = "meow";
var dog = "woof";
return [cat,dog];
};
var [cat,dog] = fn(); // Handy!
alert(cat);
alert(dog);
它是核心JS的一部分,但不知为何,直到今年我才意识到。
当你想从数组中删除一个元素时,可以使用delete操作符,如下所示:
var numbers = [1,2,3,4,5];
delete numbers[3];
//numbers is now [1,2,3,undefined,5]
正如您所看到的,元素被删除了,但是数组中留下了一个洞,因为元素被替换为一个未定义的值。
因此,要解决这个问题,不要使用删除,而是使用splice array方法…是这样的:
var numbers = [1,2,3,4,5];
numbers.splice(3,1);
//numbers is now [1,2,3,5]
splice的第一个参数是数组[index]中的序数,第二个参数是要删除的元素数量。
在创建新“对象”时,括号是可选的。
function Animal () {
}
var animal = new Animal();
var animal = new Animal;
同样的事情。
要将浮点数转换为整数,您可以使用以下神秘的技巧之一(请不要这样做):
3.14 >> 0(通过2.9999999999999999 >> .5?) 3.14 | 0(通过JavaScript中将浮点数转换为整数的最佳方法是什么?) 3.14 & -1 3.14 ^ 0 ~ ~ 3.14
基本上,对浮点数应用任何二进制操作都不会改变最终值(即恒等函数),最终会将浮点数转换为整数。