学习JavaScript(二)

[b]Checking if a Variable Exists[/b]

var result = '';
if (somevar){result = 'yes';}



A better way to check if a variable is defined is to use typeof.

if (typeof somevar !== "undefined"){result = 'yes';}
result


Because [b]somevar [/b]is undefined.

[b]Agruments[/b]
var result = sum(1, 2);
result;


[b]JavaScript is not picky at all when it comes to parameters. If you pass more parameters than the function expects, the extra parameters will be silently ignored:[/b]
>>> sum(1, 2, 3, 4, 5)
3

>>> function args() { return arguments; }
>>>args();
[]
args(1,2,3,4,true,"ninja")
[1, 2, 3, 4, true, "ninja"]
By using the arguments array you can improve the sum() function to accept any number of parameters and add them all up.

function sumOnSteroids() {
var i, res = 0;
var number_of_params = arguments.length;
for (i = 0; i < number_of_params; i++) { 
res += arguments[i];
}
return res;
}



sumOnSteroids(1, 1, 1);=3
sumOnSteroids(1, 2, 3, 4);=10

[b]var scope
[/b]

var a = 123;
function f() {
 
alert(a);
var a = 1;
alert(a);
}
f();


[color=red][b]You might expect that the first alert() will display 123 (the value of the global variable a)
the second will display 1 (the local a).[/b][/color]

[b]The first alert will show "undefined". This is because inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space.[/b][color=red][/color]

[b]
CallBack Function[/b]


function invoke_and_add(a, b){
return a() + b();
}
function one() {
return 1;
}
function two() {
return 2;
}
invoke_and_add(one, two);



When you pass a function A to another function B and B executes A, it's often said that A is a [color=red]callback [/color]function. If A doesn't have a name, then you can say that it's an [color=orange]anonymous callback[/color] function.


function multiplyByTwo(a, b, c, callback) {
var i, ar = [];
for(i = 0; i < 3; i++) {
ar[i] = callback(arguments[i] * 2);
}
return ar;
}
function addOne(a) {
return a + 1;
}


myarr = multiplyByTwo(1, 2, 3, addOne);


[b]Self-invoking Functions[/b]

(
function(name){
alert('Hello ' + name + '!');
}
)('dude')


[b]One good reason for using self-invoking anonymous functions is to have some
work done without creating global variables.
A drawback, of course, is that you cannot execute the same function twice[/b]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值