一:Javascript內置物件
1:Math模塊、
π: console.log(Math.PI)
求冪次方:console.log(Math.pow(2,10))
向上取整: console.log(Math.ceil(1.1))
向下取整: console.log(Math.floor(2.1))
四舍五入:console.log(Math.round(2.5))
取最大值:console.log(Math.max(2,1,15))
取最小值:console.log(Math.min(2,1,3,4))
范圍0~1:console.log(Math.random())
范圍0~100:console.log(Math.random()*100)
范圍50~150:console.log(Math.random()*100+50)
范圍50~150之間的整數:console.log(Math.round(Math.random()*100+50))
2:Date模塊
首先得生成物件
關鍵詞:new
da=new Date()
時間戳:console.log(da.getTime())
year=da.getFullYear()
month=da.getMonth()+1
國外的月份從0開始
date=da.getDate()
day=da.getDay()
hour=da.getHours()
minute=da.getMinutes()
second=da.getSeconds()
console.log(year,month,date,day,hour,minute,second)
二:Javascript的Windows物件
1:延遲定時器(只執行一次)
setTimeout(function(){
p.style[“color”]=‘red’
},2000)
2:間隔定時器
setInterval(function(){
執行代碼
})
終止方式:
m=setInterval(function(){
執行代碼
})
clearInterval(m)
手動停止:
<button id="b1">暫停</button>
<script type="text/javascript">
b1=document.getElementById('b1')
b1.onclick=function (){
clearInterval(m)
}
m=setInterval(function (){
window.open('https://www.youku.com/')
},2000)
</script>
3:跳轉網頁:
window.location.href=’’
m=setTimeout(function (){
window.location.href='https://www.youku.com/'
},2000)
4:打開檔案/網頁
window.open(‘網址’)
window.open(路徑)
三;Javascript的函式
定義函式:
function func(){
alert('123')
}
func()
函式的形式引數:
傳入的叫做實參,形參可以傳可以不傳,多傳只接受形參對應數量的部分
function func(x,y=3){
z=x*y
alert(z)
}
func(3,6,5) #18
函式的不定長引數:
function func(x,y=5){
console.log(arguments)
}
func(1,5,6,7,9,10)
所有的資料arguments都有,每一個引數都可以用過下標取值來獲取
用標簽使用函式:
1:<button id="b1" onclick="func()">暫停</button>
2:b1.onclick=func 弊端:不能傳參
函式的自呼叫:加載到此函式時直接呼叫
加號可以換成感嘆號‘!’也可以換成波浪線‘~’
+(function(){
執行內容化
})()
函式的作用域:
a=123
function func(){
a=456
}
func()
console.log(a) 456
加var:外部就是全域變數,內部就是區域變數,二者不會有影響
不加的話 內部的變數也是默認的全域變數
var a=123
function func(){
var a=456
}
func()
console.log(a) 123
遞回函式:
arguments.callee 表示正在運行的函式
function func(x){
if (x==1) return 1;
return x*arguments.callee(x-1);
}
五:Javascript例外處理
function func(x){
if (x==1) return 1;
return x*arguments.callee(x-1);
}
try {
n = Number(prompt('請輸入一個數字'))
alert(func(n))
}catch(e){
console.log('發生了例外'+e)
}
如果傳入的是字母,最后運算的時候格式轉不過來,就會報錯,加入例外,就會顯示自己寫入的內容,
主動拋出錯誤:
function func(x){
if (x==1) return 1;
return x*arguments.callee(x-1);
}
try {
n = Number(prompt('請輸入一個數字'))
alert(func(n))
}catch(e){
console.log('發生了例外'+e)
throw new Error('輸入錯誤')
}finally{
console.log('執行完畢')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/295430.html
標籤:其他
