JavaScript学习笔记1--语法篇摘录

本文探讨了JavaScript中假值的概念、退出循环的break语句、变量作用域的特性以及事件处理器错误的实现方式。包括常见假值的列举、break语句的用法、变量作用域的区别、以及事件处理器中内存地址共享导致的错误行为解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Here are the falsy values:

  1. false
  2. null
  3. undefined
  4. the empty string ''
  5. The number 0
  6. The number NaN

/////////////////////////////////////////////////////////////////////////////////

The break statement can optionally have a label that will cause an exit from the labeled statement, like goto....

var result = false;
point:
{
    var obj = { key: 1 };
    for (var key in obj) {
        // ...
        break point;
    }
    result = true;
}
alert(result);

/////////////////////////////////////////////////////////////////////////////////

The equality operator: ===

/////////////////////////////////////////////////////////////////////////////////

Most languages with C syntax have block scope. All variables defined in a block (a list of statements wrapped with curly braces) are not visible from outside of the block. But JavaScript does not have block scope even though its block syntax suggests that it does.

var foo = function ( ) {
var a = 3, b = 5;
var bar = function ( ) {
var b = 7, c = 11;
// At this point, a is 3, b is 7, and c is 11
a += b + c;
// At this point, a is 21, b is 7, and c is 11
};
// At this point, a is 3, b is 5, and c is not defined
bar( );
// At this point, a is 21, b is 5
};

/////////////////////////////////////////////////////////////////////////////////

对于nodes的onclick提示的i都指向同一个内存地址,所以运行的效果提示的都是nodes的个数。
// BAD EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the wrong way.
// When you click on a node, an alert box is supposed to display the ordinal of the node.
// But it always displays the number of nodes instead.
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (e) {
alert(i);
};
}
};
// END BAD EXAMPLE

// BETTER EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the right way.
// When you click on a node, an alert box will display the ordinal of the node.
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (i) {
return function (e) {
alert(e);
};
}(i);
}
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值