javascript单体内置对象

概述

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

猜你喜欢

转载自blog.csdn.net/wyw223/article/details/84944363