内置对象——Global对象和Math对象

  1 /*
  2 内置对象
  3 内置对象:“由ECMAscript实现提供的、不依赖宿主环境的对象。这些对象在ECMAscript程序执行之前就已经存在了。”
  4 
  5 1、Global(全局)对象,这个对象不存在,ECMAscript中不属于任何其他对象的属性和方法,都属于它的属性和方法。所以,事实上,并不存在全局变量和全局函数:所有在全局作用域定义的变量和函数,都是Global对象的属性和方法
  6 (Web浏览器将Global作为window对象的一部分加以实现)
  7 */
  8 
  9 //a、URI编码方法
 10 
 11 var box="//fuChong付"
 12 alert(box);    //返回//fuChong付
 13 alert(encodeURI(box));    //返回//fuChong%E4%BB%98
 14 alert(encodeURIComponent(box));    //返回%2F%2FfuChong%E4%BB%98
 15 
 16 var box="//fuChong付"
 17 var a=encodeURI(box);
 18 var b=encodeURIComponent(box);        //解码
 19 alert(decodeURI(a));
 20 alert(decodeURIComponent(b));        //解码
 21 
 22 //PS:encodeURIComponent()编码比encodeURI()编码更彻底,所以使用频率要高一些
 23 
 24 
 25 //b、enal()方法:主要担当一个字符串解析器的作用,它只接受一个参数,而这个参数就是要执行的javascript代码的字符串
 26 
 27 'var box=100'
 28 alert(box);        //不执行
 29 
 30 eval('var box=100');
 31 alert(box);        //打印100
 32 
 33 eval("function box(){return 123}");
 34 alert(box());
 35 
 36 
 37 //c、Global对象属性
 38 //Global对象包含了一些属性:undefined、NaN、Object、Array、Function等等
 39 alert(Array);    //返回构造函数
 40 
 41 
 42 //d、window对象
 43 alert(window Array);    //返回构造函数
 44 
 45 
 46 
 47 
 48 //    2、Math对象
 49 
 50 /*
 51 a、Math对象的属性
 52 
 53 属性            说明
 54 Math.E          自然对数的底数,即常量e的值
 55 Math.LN10       10的自然对数
 56 Math.LN2        2的自然对数
 57 Math.LOG2E      以2为底e的对数
 58 Math.LOG10E     以2为底e的对数
 59 Math.PI         π的值
 60 Math.SQRT1_2    1/2的平方根
 61 Math.SQRT2      2的平方根
 62 */
 63 
 64 //b、min()和max()方法
 65 alert(Math.min(1,2,46,4,1,46,3,2,6,0));    //0        最小值
 66 alert(Math.max(1,2,46,4,1,46,3,2,6,0));    //46    最大值
 67 
 68 
 69 /*
 70 c、舍入方法
 71 Math.ceil()执行向上舍入,即它总是将述职向上舍入为最接近的整数
 72 Math.floor()执行向下舍入,即它总是将述职向下舍入为最接近的整数
 73 Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数
 74 */
 75 alert(Math.ceil(20.1));        //21
 76 alert(Math.ceil(20.5));        //21
 77 alert(Math.ceil(20.9));        //21
 78 
 79 alert(Math.floor(20.1));        //20
 80 alert(Math.floor(20.5));        //20
 81 alert(Math.floor(20.9));        //20
 82 
 83 alert(Math.round(20.1));        //20
 84 alert(Math.round(20.5));        //21
 85 alert(Math.round(20.9));        //21
 86 
 87 
 88 /*
 89 d、random()方法——随机方法
 90 Math.random()方法返回介于0到1之间的一个随机数,不包括0和1,如果想大于这个范围的话,可以套用一下公式:    值=Math.floor(Math.random()*总数+第一个值)
 91 */
 92 for(var i=0;i<5;i++){
 93     document.write(Math.random());
 94     document.write("<br/>");
 95 }
 96 
 97 
 98 alert(Math.floor(Math.random()*10+1));    //范围1-10
 99 alert(Math.floor(Math.random()*10+5));    //范围4-14    10+5-1=14(5-14)
100 
101 function select(start,end){
102     var total=end-start+1;
103     return Math.floor(Math.random()*total+start);
104 }
105 alert(slect(4,14));        //用这个函数就不用计算那么麻烦,直接传入范围值就行
106 
107 
108 //e、其他方法(有很多,这里列举比较常用的)
109 方法                    说明
110 Math.abs(num)            返回num的绝对值
111 
112 alert(Math.abs(-2));    //2
View Code

 

posted @ 2013-10-24 23:40  白小虫  阅读(250)  评论(0编辑  收藏  举报