js中的函數

來源:互聯網
上載者:User

標籤:print   cap   javascrip   string   group   ring   family   function   decode   

一、函數定義的方式

(1)普通方式

文法: function 函數名(參數){

函數體

}

Code:

function method(){

alert("testMethod");

}

method();

(2)匿名函數

文法:function(參數){

函數體

}

Code:

var method = function(){

alert("yyy");

};

method();

(3)對象函數

文法:new Function(參數列表,函數體);

注意:參數名稱必須使用字串的形式,最後一個預設是函數體並且函數體需要是字串形式。

Code:

var fn = new Function("a","b","alert(a+b)");

fn(2,5);

二、函數的參數

注意:(1)形參沒有var修飾

(2)形參和實參的格式不一定相等

(3)arguments對象 是個數組 會將傳遞的實參進行封裝

Code:

function fn(a,b,c){

var sum = a+b+c;

alert(sum);

arguments是個數組 會將傳遞的實參進行封裝

for(var i=0;i<arguments.length;i++){

alert(arguments[i]);

}

}

fn(1,2,4,8);

三、函數的傳回值

(1)在定義函數的時候不必表明是否具有傳回值

(2)傳回值僅僅通過return關鍵字就可以了 return後的代碼不執行

Code:

function fn(a,b){

return a+b;

alert("xxxx");//此處的代碼不會執行

}

alert(fn(2,3));

   

四、js的全域函數

全域屬性和函數可用於所有內建的 JavaScript 對象

(1)編碼和解碼

decodeURI() 解碼某個編碼的 URI。

decodeURIComponent() 解碼一個編碼的 URI 組件。

encodeURI() 把字串編碼為 URI。

encodeURIComponent() 把字串編碼為 URI 組件。

escape() 對字串進行編碼

Code:

var url = "http://www.baidu.com?name=張&password=12//3";

alert(encodeURI(url));

//http://www.baidu.com?name=%E5%BC%A0&password=123

alert(encodeURIComponent(url));

//http%3A%2F%2Fwww.baidu.com%3Fname%3Dzhangsan%26password%3D123

alert(escape(url));

//http%3A//www.baidu.com%3Fname%3Dzhangsan%26password%3D123

(2)強制轉換

Number() 把對象的值轉換為數字。

String() 把對象的值轉換為字串。

(3)轉化為數字

parseInt() 解析一個字串並返回一個整數。

parseFloat() 解析一個字串並返回一個浮點數。

(4) eval() 計算 JavaScript 字串,並把它作為指令碼代碼來執行。

Code:

//var str = "var a=2;var b=3;alert(a+b)";

//eval(str);

function print(str){

eval(str);

}

print("自訂邏輯");

   

   

   

   

   

js中的函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.