javascript的函數

來源:互聯網
上載者:User

標籤:輸入   tag   可變參數   apply()   對象   script   undefined   function   解構賦值   

//javascript的函數//代碼1:‘use strict‘function foo(x) {    console.log(‘x= ‘ + x);    for(var i = 0; i < arguments.length; i ++) {        console.log(‘arguments[‘ + i + ‘]=‘ + arguments[i]);    }};foo(1,2,3,4,5);//代碼1解說://1.方法使用的參數可多於或少於指定數目//2.‘arguments‘關鍵字類似數組,用來顯示輸入的參數//代碼2:‘use strict‘function func1(a, b, c) {    if (arguments.length === 2) {        c = b;        b = null;    }    console.log(a + c);};func1(1,2);//代碼2解說://1.‘arguments‘關鍵字用於判斷參數傳入的個數,上面的//代碼將參數b變為可變參數//代碼3:‘use strict‘function func1(a, b, ...rest) {    console.log(a);    console.log(b);    console.log(rest);};func1(1,2,3,4,5);//1//2//[3,4,5]func1(1);//1//undefined//[]//代碼3解說://1.ES6標準引入了‘rest‘關鍵字,用來獲得剩餘的全部參數//代碼4:‘use strict‘function sum(...rest) {    var sum = 0;    for (var i = 0; i < rest.length; i ++) {        sum += rest[i];    }    return sum;};var result = sum(1,2,3,4,5);console.log(result);//15//代碼4解說://1.上面的方法sum(...rest)作用是對輸入的參數進行求和//代碼5:‘use strict‘function fun1() {    var     job = ‘cook‘,    desciption = ‘ cook delicious food‘;    console.log(job + desciption);};fun1();//代碼5解說://1.由於變數提升的存在,js函數最好在起始位置聲明所有變數//代碼6:vara = 1,b = 2;[a, b] = [b, a];console.log(a);console.log(b);//應用舉例1:交換變數a和b的值var {hostname:domain, pathname:path} = location;//應用舉例2:擷取當前頁面的網域名稱和路徑//代碼6解說://1.解構賦值的應用//代碼7:function getAge() {    var year = new Date().getFullYear();    return year - this.birthYear;}var li = {    name: ‘李‘,    birthYear: 1991,    age: getAge}var ageLi = li.age();console.log(ageLi);//27ageLi = getAge();console.log(ageLi);//NaNageLi = getAge.apply(li, []);console.log(ageLi);//27//代碼7解說://1.使用apply()方法改變this的指向//代碼8:‘use strict‘var count = 0;var oldParseInt = parseInt;window.parseInt = function() {    count += 1;    oldParseInt.apply(null, arguments);}for (var i = 0; i < 5; i ++) {    parseInt(‘19‘);}console.log(count);//代碼8解說://1.替換‘window‘對象的函數‘parseInt‘,讓它具有計數功能

  

javascript的函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.