zoukankan      html  css  js  c++  java
  • JavaScript学习笔记(六)----内置对象Global 和Math

    (一).Global对象

    所有在全局作用域中定义的属性和函数,都是Global对象的属性。例如isNaN()、isFinite()、parseInt()以及parseFloat(),实际上全是Global对象的方法。

    1. URI 编码方法 encodeURI() 和 encodeURIComponent()

    有效的URI不能包含某些字符,例如空格。而这两个URI编码方法就可以对URI进行编码,它们用特殊的UTF-8编码替换所有无效的字符,从而让浏览器能够接受和理解。 

    var uri = "http://www.baidu.com.cn/illegal value.htm#start";
    alert(encodeURI(uri));//http://www.baidu.com.cn/illegal%20value.htm#start
    alert(encodeURIComponent(uri)); //http%3A%2F%2Fwww.baidu.com.cn%2Fillegal%20value.htm%23start

    encodeURI() ---decodeURI()

    encodeURIComponent() ---decodeURIComponent()

    2. eval()方法

    eval()方法就像是一个完整的ECMAScript解析器,它只接受一个参数。

    eval(alert("hi")); //hi
    
    var msg = "hello world";
    eval(alert(msg)); //hello world
    
    eval("function sayHi(){ alert(' hello world!')}");
    sayHi(); //hello world!;
    
    
    eval("var msg1 = 'hello word';");
    alert(msg1); //hello world

    在eval()中创建的任何变量或函数都不会被提升。

    3. window对象

    ECMAScript虽然没有指出如何直接访问Global对象,但Web浏览器都是将这个全局对象作为window对象的一部分加以实现的。因此,在全局作用域中声明的所有变量和函数,就都成为了window对象的属性。

    (二) Math对象

        var num = 8 ;
        var r = Math.abs(num); //绝对值
        r = Math.ceil(3.3); //大于num的一个最小整数
        r = Math.LOG2E;//1.44269    
        alert(r);

    1) min() 和 max()方法,确定一组数值中的最大值和最小值,可以接受任意多个数值参数。

    var  max = Math.max(3,54,19,100,78);
    alert(max); //100
    
    var min = Math.min(3,54,19,100,78);
    alert(min); //3
    • 找到数组中的最大或最小值,使用apply()方法
    var numArray = [3,54,19,100,78];
    var max = Math.max.apply(Math,numArray);
    alert(max);
    
    var min = Math.min.apply(Math,numArray);
    alert(min);

    2) 舍入方法

    Math.ceil() 向上舍入

    Math.floor()向下舍入

    Math.round()四舍五入

    var num = 29.3;
    alert(Math.ceil(num)); //30
    alert(Math.floor(num));//29
    alert(Math.round(29.3));//29
    alert(Math.round(29.6));//30

    3) random()方法

     Math.random()方法返回介于0和1之间一个随机数,不包括0和1。

    公式:值 = Math.floor(Math.random()*可能值的总数 + 第一个可能的值),从某个整数范围内随机选择一个值。

    • 选择一个1到10之间的数值
    var num = Math.floor(Math.random()* 10 + 1);
    • 选择一个2到10之间的数值
    var num = Math.floor(Math.random()*9+2);
    • 选择一个介于a 到 b 之间的数值 (selectFrom()函数 by Yoyo)
    function selectFrom(lowerNum , upperNum){    
        return Math.floor(Math.random()*(upperNum-lowerNum+1)+lowerNum);
    }
    var num = selectFrom(1,4);
    alert(num);

     随机从数组中取一项,利用selectFrom()方法

    var colors=["yellow","blue","white","black","red","green"];
    var color = colors[selectFrom(0,colors.length-1)];
    alert(color);
  • 相关阅读:
    Thinkphp的import使用方法
    bug1
    setTimeout关于函数名做参数的问题
    ubuntu-12.04.5安装cacti笔记
    第七周作业
    第六周作业
    第五周作业
    第四周编程总结
    2019年春季学期第三周作业
    第二周编程总结
  • 原文地址:https://www.cnblogs.com/yanyangbyou/p/3958663.html
Copyright © 2011-2022 走看看