javascript單體內建物件
阿新 • • 發佈:2018-12-18
概述
global物件可以說是ECMAScript中最特別的一個物件了,因為不管你從什麼角度上看,這個物件都是不存在的。從某種意義上講,它是一個終極的“兜底兒物件”,換句話說呢,就是不屬於任何其他物件的屬性和方法,最終都是它的屬性和方法。我理解為,這個global物件呢,就是整個JS的“老祖宗”,找不到歸屬的那些“子子孫孫”都可以到它這裡來認祖歸宗。所有在全域性作用域中定義的屬性和函式,都是global物件的屬性和方法,比如isNaN()、parseInt()以及parseFloat()等,實際都是它的方法;還有就是常見的一些特殊值,如:NaN、undefined等都是它的屬性,以及一些建構函式Object、Array等也都是它的方法。總之,記住一點:global物件就是“老祖宗”,所有找不到歸屬的就都是它的。 ## 全域性方法 1. encodeURI() 返回編碼為有效的統一資源識別符號 (URI) 的字串,不會被編碼的字元:! @ # $ & * ( ) = : / ; ? + ' encodeURI()是Javascript中真正用來對URL編碼的函式var test = "www.zshgrwz.cn/360"
var test2 = "www.zshgrwz.cn/3 6 0"
document.write(encodeURI(test)+ "<br />")
document.write(encodeURI(test2)+ "<br />")
document.write(encodeURI("&,/?#=+:@$"))
結果:
www.zshgrwz.cn/360
www.zshgrwz.cn/3%206%200
&,/?#=+:@$
2.encodeURIComponent
對URL的組成部分進行個別編碼,而不用於對整個URL進行編碼
var test="www.zshgrwz.cn/360 "
document.write(encodeURIComponent(test)+ "<br />")
document.write(encodeURIComponent(test))
document.write(encodeURIComponent("&,/?#=+:@$"))
結果:
www.zshgrwz.cn%2F360%20%20
www.zshgrwz.cn/360
%26%2C%2F%3F%23%3D%2B%3A%40%24
3.decodeURI
可對 encodeURI() 函式編碼過的 URI 進行解碼
4.decodeURIComponent
可對 encodeURIComponent() 函式編碼的 URI 進行解碼
5.eval
eval函式的作用是在當前作用域中執行一段JavaScript程式碼字串
6.Math物件
Math是 JavaScript 的原生物件,提供各種數學功能。該物件不是建構函式,不能生成例項,所有的屬性和方法都必須在Math物件上呼叫
1.Math.abs()
Math.abs方法返回引數值的絕對值
Math.abs(1) // 1
Math.abs(-1) // 1
2.Math.max(),Math.min()
Math.max方法返回引數之中最大的那個值,Math.min返回最小的那個值。如果引數為空, Math.min返回Infinity, Math.max返回-Infinity
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
Math.min() // Infinity
Math.max() // -Infinity
3.Math.floor()
Math.floor方法返回小於引數值的最大整數(地板值)
Math.floor(3.2) // 3
Math.floor(-3.2) // -4
4.Math.ceil()
Math.ceil方法返回大於引數值的最小整數(天花板值)
Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3
5.Math.round()
Math.round(0.1) // 0
Math.round(0.5) // 1
Math.round(0.6) // 1
// 等同於
Math.floor(x + 0.5)
6.Math.random()
Math.random()返回0到1之間的一個偽隨機數,可能等於0,但是一定小於1
Math.random() // 0.7151307314634323
任意範圍的隨機數生成函式如下
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
getRandomArbitrary(1.5, 6.5)
// 2.4942810038223864
任意範圍的隨機整數生成函式如下
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
getRandomInt(1, 6) // 5