大蟒蛇python教程共享Python全栈之学习JS(2)

目录
  • 1. js对象
    • 1.1 object对象
    • 1.2 json对象
  • 2. js字符串函数
    • 3. js数组相关方法
      • 4. js数学对象相关方法
        • 5. bom对象
          • 5.1 定时器
          • 5.2 获取年月日时分秒
          • 5.3 navigator
          • 5.4 历史对象
        • 6. bom对象location
          • 7. 小提示
            • ceshi.html:
          • 总结

            1. js对象

            1.1 object对象

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>object对象</title>  </head>  <body>      <script>          // 1.定义对象方法一          var obj = new object();          console.log(obj , typeof(obj))          obj.name = "孙坚";          obj.age = 18;          obj.weight = "200斤";          obj.eat = function(){              alert("我会吃竹子");          }          console.log(obj.name)          // obj.eat();          //2.定义对象方法二          /* 对象中的成员不要使用单引号,在特殊场景中,比如json格式字符串的转换中会报错; */          var obj = {              name:"张三",              "age" : 20,              sex   : "男性",              drink : function(something){                  console.log("我会喝牛栏山",something);              }          }          //调用方式一          console.log(obj.sex)          obj.drink("老白干")          //调用方式二          console.log(obj["age"])          obj["drink"](1)          // 注意点          var str = "name"          console.log(obj.str , "<==========================>") //error          console.log(obj.name)          console.log(obj[str]) // obj["name"]          // eval 可以把字符串当成代码执行          eval("console.log(333)")          //3.定义对象方法三          /* 类比python中定义类的写法 , this等价于self */          function person(name,age,sex){              this.name = name;              this.age = age;              this.sex = sex;              this.func = function(){                  console.log("我是func");                  return this.sex;              }          }          var obj1 = new person("刘一风",30,"男性");          var obj2 = new person("张三风",90,"女性");          console.log(obj1.name);          var res = obj1.func();          console.log(res);          console.log(obj2.name)          var res = obj2.func();          console.log(res);          //4.遍历对象           for(var i in obj1){              console.log(i)          }          //5. with(对象) 语法可以直接获取对象成员的值          with(obj1){              console.log(name);              console.log(sex);              console.log(age);              res = func();              console.log(res);          }          console.log("<===================================>")          //将4和5结合,遍历对象中的数据;          for(var i in obj1){              //console.log(i , typeof(i)) // name age sex func  ... string              with(obj1){                  console.log(eval(i))              }          }        </script>  </body>  </html>  

            1.2 json对象

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>json对象</title>  </head>  <body>      <script>          var data = {              'name':"文东",              age:20,              "sleep":function(){                  alert("文东一天睡23小时,还有一个小时上厕所.");              }          }          // js对象 => json格式的字符串          var res = json.stringify(data);          console.log(res , typeof(res)); // {"name":"文东","age":20}           // json格式的字符串 => js对象          res = '{"name":"东东","age":30}';  // success          // res = "{'name':90,'age':40}"; error 引号必须是双引号          var res2 = json.parse(res);          console.log(res2,typeof(res2));        </script>  </body>  </html>  

            2. js字符串函数

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>字符串对象的相关方法</title>  </head>  <body>      <script>          var string = "to be or not to be";          //获取字符串长度 length	          var res = string.length          var res = string[-1]          console.log(res)          //1.清除两侧的空白 trim [ python的strip ]          var res = string.trim()          console.log(string)          console.log(res)          //2.获取首次出现的位置 indexof   [ python的find ]           /*找不到返回-1*/          var string = "to be or not to be";          var res = string.indexof("z")          console.log(res)          //3/最后一次出现的位置 lastindexof           /*找不到返回-1*/          var res = string.lastindexof("zzz")          console.log(res);          //4.连接字符串	concat	 [ python的 os.path.join  + ]          var res = string.concat("d:\","python32\","day42");          console.log(res);          //5.截取字符串 slice          /* string.slice(开始值,结束值) 字符串的切片  留头舍尾  [支持逆向下标]*/          var string = "11122233e or not to be";          var res = string.slice(1,7);          var res = string.slice(-5,-1);      // to b          // var res = string.slice(-5,-10); //截取不到返回空          console.log(res,"<==1==>")          //6.截取字符串 substr          /* string.substr(开始值,截取几个) */          var string = "11122233e or not to be";          var res = string.substr(3,4)          console.log(res,"<==2==>")          //7.拆分字符串 split  [ python的 split ]          var string = "11122233e or not to be";          var res = string.split(" ")          console.log(res,"<==3==>")          //8.大小写 touppercase tolowercase          var string = "11122233e or not to be";          res = string.touppercase();          res = string.tolowercase();          console.log(res,"<==4==>")          //9.search 匹配第一次找到的索引位置,找不到返回-1          var string = "aaabbb oldaoy ccc"          var res = string.search(/oldboy/)          console.log(res,"<==5==>")          //10.match 返回匹配的数据          /* /正则表达式/修饰符 g:全局匹配 i:不区分大小写 m:多行匹配  */          var string = "我的电话是 : 13838384388 你的电话是: 13854381438"          var res = string.match(/d{11}/);  // 匹配一个          var res = string.match(/d{11}/g); // 匹配多个,(需要修饰符加上g)          console.log(res)          console.log(res[0])          console.log(res[1])          //11.字符串替换 replace          /* replace默认只替换一次 */          var string = "to be or not to be";          var res = string.replace("to","two")          console.log(res,"<==6==>")                 // 方法一:          function myreplace(string,a,b){              /*                  找最后一个to,如果找不到返回-1                  如果能找到就不停的进行替换,直到-1为止,循环终止;              */              while(string.lastindexof(a) != -1){                  console.log(1)                  string = string.replace(a,b);              }              return string;          }               var string = "to be or not to be";             var res = myreplace(string,"to","two")          console.log(res) // two be or not two be          // 方法二          var string = "to be or not to be";          var res = string.replace(/to/g,"two");          console.log(res)      </script>  </body>  </html>  

            3. js数组相关方法

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>数组对象的相关方法</title>  </head>  <body>      <script>          // 1.定义一个数组          var arr = array();          var arr = array(10,11,12);          var arr = [15,16,17]          console.log(arr , typeof(arr))          // ### 1.增          var arr = [];          arr[0] = 10;          arr[1] = 11;          arr[2] = 12;          // js特征:允许在一个临时的索引值上插入数据; ok          arr[10] = 50;          console.log(arr)          console.log(arr[5])            // (1)push 从数组的最后插入元素  相当于python的append          var arr = [];          var res = arr.push(111);          var res = arr.push(222);          var res = arr.push(333);          console.log(res,arr)          // (2)unshift 从数组的前面插入元素 相当于python的insert          var arr = [100,101];          var res = arr.unshift(1);          var res = arr.unshift(333);          console.log(res , arr);          // (3)concat 迭代追加数据 相当于python的extend          var arr1 = [1,2,3]          var arr2 = ["你好","我好","她也好"]          var res = arr1.concat(arr2)          console.log(res, typeof(res));          // ###2删          // (1) delete 删除          /* 把值删掉了,原位置用空来取代,返回undifined */          var arr = [1, 2, 3, "你好", "我好", "她也好"];          delete arr[1];          console.log(arr);          console.log(arr[1])          // (2)pop  从后面删除;          var arr = [1, 2, 3, "你好", "我好", "她也好"];          var res = arr.pop();          console.log(res ,arr);          // (3)shift 从前面删除          var arr = [1, 2, 3, "你好", "我好", "她也好"];          var res = arr.shift()          console.log(res , arr)          // ###  特别splice  从指定位置往后进行删除或者添加          /* arr.splice(从第几个位置开始,删除几个,[可选的是添加的元素])   */          var arr = [1, 2, 3, "你好", "我好", "她也好"];          // 从第二个2位置开始,删除2个          var res = arr.splice(2,2)          console.log(res , arr)          // 从第二个2位置开始,删除0个,添加,"hello","world"          var arr = [1, 2, 3, "你好", "我好", "她也好"];          var res = arr.splice(2,0,"hello","world")          console.log(res , arr)          // ###3改查          var arr = [1, 2, 3, "你好", "我好", "她也好"];          //修改元素          arr[3] = "你不好";          //获取元素          console.log(arr[3]);          console.log(arr);          // ###4 其他方法          // 拼接字符串  join          /* split 和 join 是一对;*/          var arr = ["you","can","you","up"];          var res = arr.join("#")          console.log(res)          // 数组元素反转 reverse          var arr = [100,200,3,150];          var res = arr.reverse();          console.log(res);          // 截取数组的一部分 slice           /* arr.slice(开始值,结束值) 数组的切片  留头舍尾  [支持逆向下标]*/          var arr = ["宋健","何旭彤","刘利伟","高雪峰","戈隆","王致和","马生平"]          var res = arr.slice(2)          // var res = arr.slice(2,4)          var res = arr.slice(-3,-1)          console.log(res);          // 排序 默认升序 sort          var arr = [1,2,3,4,9,22,21];          var arr = ["1","2","3","4","9","22","21"];          var res = arr.sort()          console.log(res)          var arr = [100,1,2,3,4,9,22,21];          // sorted 里面的参数是一个函数,通过函数进行升序或者降序排序;          /* return 1代表交换位置,如果return -1 代表不交换位置 */          var res = arr.sort(function(a,b){              if(a>b){                  return -1;              }else{                  return 1;              }                         });          console.log(res)      </script>      <!--       python : 冒泡排序          nums = [1,22,3,2,4,9,21];      def bubble_sort(nums):          for i in range(len(nums) - 1):  # 这个循环负责设置冒泡排序进行的次数              for j in range(len(nums) - i - 1):  # j为列表下标                  if nums[j] > nums[j + 1]:                      nums[j], nums[j + 1] = nums[j + 1], nums[j]              break;          return nums      res = bubble_sort(nums)      print(res) -->  </body>  </html>          

            4. js数学对象相关方法

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>数学对象中的相关方法</title>  </head>  <body>      <script>          //四舍五入round          var res = math.round(3.5)          var res = math.round(2.5)          var res = math.round(2.31)          console.log(res)          //最大值 max                  var res = math.max(1,2,3,4,34343);          //最小值 min          var res = math.min(1,2,3,4,34343);          //绝对值 abs          var res = math.abs(-90);          console.log(res)          //向下取整 floor 地板          var res = math.floor(3.001)          //向上取整 ceil 天花板          var res = math.ceil(3.990)          //幂运算 pow          var res = math.pow(2,3)          //开方运算 sqrt                       var res = math.sqrt(9)          console.log(res)          // ### 随机值推导公式          //获取从0到1随机值   0<x<1          var res = math.random()          console.log(res)          //获取1~10的随机值 1 <= x <= 10          var res = math.ceil(math.random() * 10 )          console.log(res)          // 1.获取从 m 到 n 的随机值   5,14  m=5 , n=14          // 1 <= x <= 10  =>  1+4 <= x <= 10+4 < 5 <= x <= 14          var res = math.ceil(math.random() * 10 ) + 4          //  m = 5 , n = 14          // 2.拆解数字,把对应的m和n进行替换;          var res = math.ceil(math.random() * (14-5+1) ) + (5 - 1)          // 3.推出最后结果          var res = math.ceil(math.random() * (n-m+1) ) + (m - 1)          // 4.封装函数:终极版:随机值;          function randrange(m,n){              return math.ceil(math.random() * (n-m+1) ) + (m - 1);          }        </script>  </body>  </html>  

            5. bom对象

            5.1 定时器

            <!doctype html><html lang="en"><head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>bom对象 </title></head><body>    <script>        /*### bomjs bom对象  : 针对于浏览器的控制   browser object model js 中最大的对象 window 整个浏览器窗口出现的所有内容行为都是window对象中的成员;        */        console.log(window)        // 1.弹出警告框        // window.alert('你好')        // 2.确认弹窗        // var res = window.confirm("确认弹窗")        // console.log(res); // true / false        // 3.等待输入弹窗        // var res = window.prompt("请输入您的银行密码:")        // console.log(res);        // 4.关闭浏览器窗口        // window.close();        // innerheight innerwidth 获取浏览器窗口内部的宽和高        console.log(`浏览器窗口内部的宽度${window.innerwidth}`)        console.log(`浏览器窗口内部的高度${window.innerheight}`)        // window.open("https://www.baidu.com","_self"); // 在当前页面跳转        // window.open("https://www.baidu.com","_blank","width=500,height=500");   // 在新窗口页面跳转        // ###定时器        /*            # 定时器种类(两种):基于单线程的异步并发程序;            window.setinterval(函数名,间隔时间(毫秒))   // 定时执行多次任务            window.settimeout(函数名,间隔时间(毫秒))    // 定时执行一次任务            window.clearinterval(id号)  // 清除定时器 setinterval            window.cleartimeout(id号)   // 清除定时器 settimeout        */        var num = 1        function func(){            console.log(`我执行了${num}`);            num++;        }        var id1 = window.setinterval(func,1000);        var id2 = window.settimeout(func,2000);        console.log(id1,"id1")        console.log(id2,"id2")        console.log("我执行完了....")        window.clearinterval(id1)    </script>    </body></html><!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>bom对象 </title>  </head>  <body>      <script>          /*  			### bom  			js bom对象  : 针对于浏览器的控制   browser object model   			js 中最大的对象 window 整个浏览器窗口出现的所有内容行为都是window对象中的成员;          */          console.log(window)          // 1.弹出警告框          // window.alert('你好')          // 2.确认弹窗          // var res = window.confirm("确认弹窗")          // console.log(res); // true / false          // 3.等待输入弹窗          // var res = window.prompt("请输入您的银行密码:")          // console.log(res);          // 4.关闭浏览器窗口          // window.close();          // innerheight innerwidth 获取浏览器窗口内部的宽和高          console.log(`浏览器窗口内部的宽度${window.innerwidth}`)          console.log(`浏览器窗口内部的高度${window.innerheight}`)          // window.open("https://www.baidu.com","_self"); // 在当前页面跳转          // window.open("https://www.baidu.com","_blank","width=500,height=500");   // 在新窗口页面跳转          // ###定时器          /*              # 定时器种类(两种):基于单线程的异步并发程序;              window.setinterval(函数名,间隔时间(毫秒))   // 定时执行多次任务              window.settimeout(函数名,间隔时间(毫秒))    // 定时执行一次任务              window.clearinterval(id号)  // 清除定时器 setinterval              window.cleartimeout(id号)   // 清除定时器 settimeout          */          var num = 1          function func(){              console.log(`我执行了${num}`);              num++;          }          var id1 = window.setinterval(func,1000);          var id2 = window.settimeout(func,2000);          console.log(id1,"id1")          console.log(id2,"id2")          console.log("我执行完了....")          window.clearinterval(id1)      </script>  </body>  </html>  

            5.2 获取年月日时分秒

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>获取年月日时分秒</title>      <style>          #clock          {              width:500px;              height:50px;              border:solid 1px red;              border-radius: 25px;              text-align: center;              line-height: 50px;              background-color: chartreuse;              color:red;          }      </style>  </head>  <body>      <div id="clock"> </div>      <script>          var obj = document.getelementbyid("clock");          console.log(obj)          function func(){              var d = new date();              console.log(d);              // 获取年份              var year = d.getfullyear()              // 获取月份 月份范围 0 ~ 11 0代表1月份              var month = d.getmonth()              // 获取日期              var date = d.getdate()              // 获取小时              var hour = d.gethours()              // 获取分钟              var minutes = d.getminutes()              // 获取秒数              var seconds = d.getseconds()              strvar= `现在的时间是: ${year}年-${month+1}月-${date}日  ${hour}:${minutes}:${seconds}`;              console.log(strvar);              obj.innerhtml = strvar              console.log(minutes, typeof(minutes));              // 清除定时器的效果              if(minutes == 8){                  clearinterval(id);              }          }          var id = window.setinterval(func,1000)        </script>  </body>  </html>  

            5.3 navigator

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>bom模型中 navigator 对象 </title>  </head>  <body>      <script>          console.log(navigator);          console.log(navigator.platform)  // 判断是pc端还是移动端          console.log(navigator.useragent) // 在爬虫程序中,可以伪造成浏览器进行数据爬取,绕开服务端的反爬机制;      </script>  </body>  </html>  

            5.4 历史对象

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>document</title>  </head>  <body>      <button onclick="func1()">查看历史对象</button>      <button onclick="func2()">跳转到上一页</button>      <button onclick="func3()">跳转到下一页</button>      <button onclick="func4()">当前页面刷新</button>      <script>          function func1(){              console.log(history);          }          function func2(){              history.go(-1);          }          function func3(){              // history.go(1);              history.go(2);          }          function func4(){              history.go(0);          }      </script>  </body>  </html>  

            6. bom对象location

            location作用: 负责刷新页面,跳转页面用的,可以获取地址栏上面的参数

            <!doctype html>  <html lang="en">  <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>bom对象 location</title>  </head>  <body>      <button onclick="func1()">查看location对象</button>      <button onclick="func2()">跳转其他页面</button>      <button onclick="func3()">刷新页面</button>      <button onclick="func4()">过一秒在刷新页面</button>      <script>          function func1(){              /* 链接地址:  https://ip + 端口号 + 路径 + 参数 + 锚点 */              console.log(location);              console.log(`协议:${location.protocol}`);              console.log(`ip端口号:${location.host}`);              console.log(`端口号:${location.port}`);              console.log(`路径:${location.pathname}`);              console.log(`获取锚点:${location.hash}`);              console.log(`获取地址栏参数:${location.search}`);              console.log(`完全地址:${location.href}`)          }          //跳转页面          function func2(){              // location.href = "https://www.baidu.com";方法一              location.assign("https://www.jd.com");          }          //刷新页面          function func3(){              location.reload();          }          // 过一秒在刷新页面          function func4(){              settimeout(func3,1000);              console.log("我执行了...")          }          // 每过一秒刷新一下页面          /* 等待所有页面图片文字全部加载完毕之后,再去执行对应的代码 */          window.onload = function(){              func4()          }      </script>  </body>  </html>  

            7. 小提示

            js三大对象  1. 本地对象:js语法  2. bom对象:浏览器相关的成员(针对于浏览器的控制)brower object model  3. dom文档对象:关于html文件节点相关的数据、相关的值(针对于html的控制) document object model  js是单线程的异步程序  定时器是单线程的异步程序(例子)  

            ceshi.html:

            <!doctype html>  <html lang="en">  <head>   <meta charset="utf-8">   <title>document</title>   <style>   *{margin:0;   padding:0;   list-style:none;}   .wrap{height:170px;   width:490px;   margin:60px auto;   overflow: hidden;   position: relative;   margin:100px auto;}   .wrap ul{position:absolute;}    .wrap ul li{height:170px;}   .wrap ol{position:absolute;   right:5px;   bottom:10px;}   .wrap ol li{height:20px; width: 20px;   background:#ccc;   border:solid 1px #666;   margin-left:5px;   color:#000;   float:left;   line-height:center;   text-align:center;   cursor:pointer;}   .wrap ol .on{background:#e97305;   color:#fff;}   </style>   <script type="text/javascript">   window.onload=function(){   var wrap=document.getelementbyid('wrap'),   pic=document.getelementbyid('pic').getelementsbytagname("li"),   list=document.getelementbyid('list').getelementsbytagname('li'),   index=0,   timer=null;   // 定义并调用自动播放函数   timer = setinterval(autoplay, 2000);   // 鼠标划过整个容器时停止自动播放   wrap.onmouseover = function () {   clearinterval(timer);   }   // 鼠标离开整个容器时继续播放至下一张   wrap.onmouseout = function () {   timer = setinterval(autoplay, 2000);   }   // 遍历所有数字导航实现划过切换至对应的图片   for (var i = 0; i < list.length; i++) {   list[i].onmouseover = function () {   clearinterval(timer);   index = this.innertext - 1;   changepic(index);   };   };   function autoplay () {   if (++index >= pic.length) index = 0;   changepic(index);   }   // 定义图片切换函数   function changepic (curindex) {   for (var i = 0; i < pic.length; ++i) {   pic[i].style.display = "none";   list[i].classname = "";   }   pic[curindex].style.display = "block";   list[curindex].classname = "on";   }   };   </script>   </head>  <body>   <div class="wrap" id='wrap'>   <ul id="pic">   <li><img src="../image/img1.png" alt=""></li>   <li><img src="../image/img2.png" alt=""></li>   <li><img src="../image/img3.png" alt=""></li>   </ul>   <ol id="list">   <li class="on">1</li>   <li>2</li>   <li>3</li>   <li>4</li>   <li>5</li>   </ol>   </div>  </body>  </html>  

            总结

            本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注<计算机技术网(www.ctvol.com)!!>的更多内容!

            需要了解更多python教程分享Python全栈之学习JS(2),都可以关注python教程分享栏目—计算机技术网(www.ctvol.com)!

            本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

            ctvol管理联系方式QQ:251552304

            本文章地址:https://www.ctvol.com/pythontutorial/1041669.html

            (0)
            上一篇 2022年1月29日
            下一篇 2022年1月29日

            精彩推荐