JavaScript函數認識,Js中的常見函數
JavaScript函數:
也稱為方法,用來存儲一塊代碼,需要的時候調用。
函數是由事件驅動的或者當它被調用時執行的可重復使用的代碼塊。
函數需要包含四要素:返回類型,函數名,參數列表,函數體
拓展:強類型語言的函數
public int Sun(int a,int b){ return = a+b; }
return返回,Sun函數名,int a,int b,參數列表,int 整型。
沒有返回值的函數:
public void Sun(int a,int b){ } Sun(1,2);
這樣的參數a,b是形參,也就是形式參數,調用函數是給的參數1,2是實參,也就是實際參數。
JavaScript中的函數定義:
//定義函數jiSun function jiSuan(){ alert("這是函數jiSuan"); } //調用函數 jiSuan();
function是定義函數,並不會執行,調用函數時才會尋找該函數名的定義內容。
JavaScript中函數的定義和調用先後順序可以先寫調用在寫定義。
有參數的函數:
//有參數的函數 function jiSuan(a,b){ alert(a+b); } //調用函數 jiSuan(3,5);
需要註意的是定義函數是的形參並不需要用var定義。
有返回值的函數:
function jiSuan(a,b){ return a+b; } //調用函數 var c=jiSuan(3,5); alert(c);
返回值返回給調用函數,一般定義一個變量把返回值賦給變量。
補充:強類型語言中有默認值的函數,js不支持有默認值的函數
function jiSuan(a,b=2){ alert(a+b); } //調用函數 jiSuan(3);
JavaScript中的常用函數:
document.write(""); 輸出語句
Math.random();
document.write(Math.random());
document.write(parseInt(Math.random()*10));
日期時間類函數:
//獲取當前時間 document.write(Date());
//獲取當前時間 var d=new Date(); //獲取當前時間戳 document.write(d.getTime());
//獲取當前時間 var d=new Date(); //獲取當前年份 document.write(d.getFullYear());
//獲取當前時間 var d=new Date(); //獲取當前月份,註意這裏需要+1 document.write(d.getMonth()+1);
//獲取當前時間 var d=new Date(); //獲取當前幾號 document.write(d.getDate());
//獲取當前時間 var d=new Date(); //獲取當前幾時 document.write(d.getHours());
//獲取當前時間 var d=new Date(); //獲取當前幾分 document.write(d.getMinutes());
//獲取當前時間 var d=new Date(); //獲取當前幾秒 document.write(d.getSeconds());
//獲取當前時間 var d=new Date(); //獲取當前星期幾 document.write(d.getDay());
//獲取當前時間 var d=new Date(); //獲取當前幾毫秒 document.write(d.getMilliseconds());
數學類函數:
//向上取整 document.write(Math.ceil(3.5));
//向下取整 document.write(Math.floor(3.5));
//取絕對值 document.write(Math.abs(-2)); //四舍五入 document.write(Math.round(5.5)); //返回最高值 document.write(Math.max(5,7)); //返回最低值 document.write(Math.round(5.7)); //返回兩個數的次冪 document.write(Math.pow(5.7)); //返回平方根 document.write(sqrt.round(5));
字符串函數:
var str="hello world"; var s="l"; //返回字符在字符串中第一次出現的位置 document.write(str.indexOf(s)); //返回指定位置的字符 document.write(str.charAt(0)); //返回字符在字符串中最後一次出現的位置 document.write(str.lastIndexOf(s)); //截取字符串 document.write(str.substring(1,3)); //截取字符串相應的長度 document.write(str.substr(1,3));
var str="hello world"; //替換相應字符串 str=str.replace("hell","^^"); document.write(str);
var str="hello world"; //替換所有相應字符串 str=str.replace(/l/g,"^^"); document.write(str);
//split拆分字符串,通過將字符串劃分成子串,將一個字符串做成一個字符串數組。 var str="hello world"; var arr=str.split(" ");
如上字符串"helllo world"會被空格拆分成數組,第一個值hello,第二個值world
其他:
length 屬性
返回字符串的長度,所謂字符串的長度是指其包含的字符的個數。
toLowerCase
將整個字符串轉成小寫字母。
var lower_string = a.toLowerCase();
//lower_string = "hello"
toUpperCase
將整個字符串轉成大寫字母。
var upper_string = a.toUpperCase();
//upper_string = "HELLO"
search
執行一個正則表達式匹配查找。如果查找成功,返回字符串中匹配的索引值。否則返回 -1 。
var index1 = a.search(re);
//index1 = 0
var index2 = b.search(re);
//index2 = -1
補充:
變量名的命名規範:一般以字母開頭,一般都用小寫字母,盡量不出現特殊符號
函數名的命名規範:駝峰法,首字母小寫,其他每個單詞首字母大寫
JavaScript函數認識,Js中的常見函數