var myArray = [];
myArray[myArray.length] = 'New Element';
2,調整一個數組的長度
Length屬性不是只讀的,所以你可以設置Length屬性的值。而且,你可以使用它增大或縮小數組的長度。例如:
var myArray = [1,2,3];
myArray.length // 3
myArray.length = 2; //Delete the last element
myArray.length = 20 // add 18 elements to the array; the elements have the undefined value.
5,瞭解一個函數需要多少個變量
這是一個偉大的技巧,可以讓你準確地知道一個函數需要多少個變量。例如:
function add_nums(num1, num2){
return num1 + num2;
}
add_nums.length // 2 is the amount of parameters expected by the function add_nums
6,使用「arguments」對象來瞭解一個函數接收到了多少個參數
這個技術可以讓你使用「arguments」對象來瞭解一個函數接收到了多少個參數。例如:
function add_nums(){
return arguments.length;
}
add_nums(23,11,32,56,89,89,89,44,6); //this return the number 9
當你需要檢查參數個數的有效性的時候,或者當你需要創建一個不確定參數個數的函數的時候,這個技巧是很有用的。
function sum_three_nums( ){
if(arguments.length!=3) throw new Error('received ' + arguments.length + ' parameters and should work with 3');
}
sum_three_nums(23,43); //Return the error message
function sum_num(){
var total = 0;
for(var i=0;i<arguments .length;i++){
total+=arguments;
}
return total;
}
sum_num(2,34,45,56,56);作者: gswdkimo 時間: 2010-12-31 18:47
7,把對象當成參數,來組織和改善函數
在現代Web開發中,對象最普遍的一個用途是把它們當成函數的參數。要記住函數參數的這個規則總是很困難的;但是,使用一個對象是十分有好處的,因為我們不必再擔心參數的規則了。而且,它更有組織性,可以讓用戶更好的理解我們要做什麼。
這個方法可以讓你把對象當成參數,來組織和改善函數。例如:
function insertData(name,lastName,phone,address){
code here;
}
重構以後的代碼是這樣的:
function insertData(parameters){
var name = parameters.name;
var lastName = parameters.lastName;
var phone = parameters.phone;
var address = parameters.address;
}
當你要使用默認值的時候,它也是十分有用的。例如:
function insertData(parameters){
var name = parameters.name;
var lastName = parameters.lastName;
var phone = parameters.phone;
var address = parameters.address;
var status = parameters.status || 'single' //If status is not defined as a property
//in the object the variable status take single as value
}
8,函數就是數據
函數就是像strings或numbers那樣的數據,我們可以把它們當成函數參數來傳遞它們,這可以創建十分令人驚訝而又「威風凜凜」的Web應用程序。這個方法是非常有用的,幾乎所有的主流框架都使用了這個方法。例如:
function byId(element, event, f){
Document.getElementById(element).['on'+event] = f; //f is the function that we pass as parameter
}
byId('myBtn','click',function(){alert('Hello World')});
Another example of functions as data:
//Example 1
function msg(m){
Alert(m);
}
//Example 2
var msg = function(m){ alert(m);}
這些函數幾乎是完全相同的。唯一的區別是使用它們的方式。例如:第一個函數,在你聲明它以前,你就可以使用它了;但是第二個函數只有聲明以後才能使用:
//Example 1
msg('Hello world'); //This will work
function msg(m){
alert(m);
}
//Example 2
msg('Hello world'); //Does not work because JavaScript cannot find the function msg because is used before is been declared.
var msg = function(m){ alert(m)}
9,擴展本地對象
雖然一些JavaScript的領袖不推薦這個技術,但是它已經被一些框架使用了。它可以讓你針對JavaScript API來創建一些輔助性的方法。
//We create the method prototype for our arrays
//It only sums numeric elements
Array.prototype.sum = function(){
var len = this.length;
total = 0;
for(var i=0;i<len ;i++){
if(typeof this[ i ]!= 'number') continue;
total += this[ i ];
}
return total;
}
var myArray = [1,2,3,'hola'];
myArray.sum();