zoukankan      html  css  js  c++  java
  • JavaScript常用对象

    一、创建对象

    1. 构造函数

      • 使用new操作符后跟Object构造函数
      // 创建对象
      var person = new Object();
      // 给对象添加name和age属性
      person.name = 'jack';
      person.age = 28;
      // 给对象添加fav的方法
      person.fav = function(){
          console.log('泡妹子');
      }
      
      // 特殊:
      var person = {};    // 与new Object()相同
      
    2. 使用对象字面量表示法

      • 对象字面量是对象定义的一种简写形式,目的在于简化创建包含大量属性的对象的过程
      var person = {
          name : 'jack';
          age : 28,
          fav : function(){
              console.log('泡妹子');
          }
      }
      
      • this指向
        • 对象中的this指向当前对象
        • 全局作用域中的this,一定指向window
        • 函数中的this,一般情况下,都指向window
          • 特殊情况:使用call和apply,此时this指向传入的对象
        • 自执行函数中的this,一定指向window
      var obj = {};
      obj.name = 'mjj';
      obj.fav = function(){		
          console.log(this);		// 此时this指向当前对象,即obj 
      }
      
      console.log(this);			// 此时this指向window
      function  add(x,y) {
          console.log(this.name);
      }
      add();					   // 空值,此时this指向window
      add.call(obj,1,2);		    // 此时this指向传入的对象,即obj
      add.apply(obj,[1,2]);		// 此时this指向传入的对象,即obj
      
      (function () {
          console.log(this);		// 此时this指向window
      })()
      
    3. 访问对象中属性的方法

      • 点语法:用来访问对象中的属性
      person.name;    		// jack
      person.fav();   		// 泡妹子
      
      • 括号表示法
      person['name'];  		// 相当于person.name;
      
    4. 遍历对象

      var obj = {};
      for (var key in obj){
          obj[key]
      }
      
    5. 面向对象

      // 使用构造函数来创建对象
      function Point(x, y) {
        this.x = x;
        this.y = y;
      }
      Point.prototype.toString = function () {
        return '(' + this.x + ', ' + this.y + ')';
      };
      var p = new Point(1, 2);
      
      // es6用class来创建对象
      class Person{
          constructor(name,age){
              // 初始化
              this.name = name;
              this.age = age;
          }
          fav(){
              console.log(this.name);
          }
      }
      var p = new Person('mjj',18);
      p.fav();
      

    二、常用对象

    2.1 数组:Array

    1. 数组的创建方式

      • 跟object创建对象一样,使用Array构造函数方式创建
      var colors = new Array();
      
      • 使用字面量方式创建数组
      var colors = [];
      
    2. Array.isArray():确定某个值到底是否是数组

      var colors = ['red','green','blue'];
      Array.isArray(colors);      	// true
      
    3. toString():返回由数组中每个值以一个以逗号拼接成的字符串

      var colors = ['red','green','blue'];
      alert(colors.toString());    	// red,green,blue
      
    4. join方法:返回由数组中每个值以相同符号拼接成的字符串

      var colors = ['red','blue','green'];
      colors.join('||');          	// red||blue||green
      
    5. 栈方法:LIFO(后进先出)

      • push():进,可以接收任意数量的参数,把它们逐个添加到数组末尾,并返回修改后数组的长度
      var colors = [];
      var count = colors.push('red','blue','green');
      alert(count);      			// 3
      
      • pop():出,从数组末尾移除最后一项,减少数组的length值,然后返回移除的项
      var item = colors.pop();     // 取最后一项
      alert(item); 			    // green
      alert(colors.length);        // 2
      
    6. 队列方法:FIFO(先进先出)

      • unshift():进,在数组前端添加任意个项并返回新数组的长度
      var colors = [];
      var count  = colors.unshift('red','green');  // 推入两项
      alert(count); 		    	// 2
      console.log(colors);     	// ["red", "green"]
      
      • shift():出,移除数组中的第一个项并返回该项,同时将数组长度减1
      var colors = ['red','blue','green'];
      var item = colors.shift();       // 取得第一项
      alert(item); 		    	// "red"
      alert(colors.length);    	// 2
      
    7. 重排序方法

      • reverse():反转,翻转数组项的顺序
      var values = [1,2,3,4,5];
      values.reverse();
      alert(values); 			// 5,4,3,2,1
      
      • sort():排序,默认是升序排列
      // 升序
      function compare(v1,v2){
          if(v1 < v2){
              return -1;
          }else if (v1 > v2){
              return 1;
          }else{
              return 0;
          }
      }
      var values = [0,1,5,10,15];
      values.sort(compare);
      alert(values);           // 0,1,5,10,15
      // 降序
      function compare(v1,v2){
          if(v1 < v2){
              return 1;
          }else if (v1 > v2){
              return -1;
          }else{
              return 0;
          }
      }
      var values = [0, 1, 5, 10, 15];
      values.sort(compare);
      alert(values);    		// 15,10,5,1,0
      
    8. 操作方法

      • concat():数组合并方法,一个数组调用concat()方法去合并另一个数组,返回一个新的数组,接收的参数是可以是任意的
        • 参数为一个或多个数组,会将这些数组中每一项都添加到结果数组中。
        • 参数不是数组,这些值就会被简单地添加到结果数组的末尾
      var colors = ['red','blue','green'];
      colors.concat('yello');           		 // ["red", "blue", "green", "yello"]
      colors.concat({'name':'张三'});           // ["red", "blue", "green", {…}]
      colors.concat({'name':'李四'},['black','brown']);  
      // ["red", "blue", "green", {…}, "black", "brown"]
      
      • slice():基于当前数组中一个或多个项创建一个新数组,可以接受一或两个参数,要返回项的起始和结束位置
        • 一个参数的情况下,返回从该参数指定位置开始到当前数组默认的所有项
        • 两个参数的情况下,返回起始和结束位置之间的项,但不包括结束位置的项
      var colors = ['red','blue','green','yellow','purple'];
      // 正值情况下
      colors.slice(1);	    // ["blue", "green", "yellow", "purple"]
      colors.slice(1,4);      // ["blue", "green", "yellow"]
      // 负值情况下
      colors.slice(-2,-1);	// ["yellow"] 
      colors.slice(-1,-2);	// []
      
      • splice():给数组插入、删除、替换项
        • 插入:向指定位置插入任意数量的项,只需提供3个参数:起始位置,0(要删除的个数),要插入的项
        • 删除:删除任意数量的项,只需指定2个参数:要删除的第一项的位置,要删除的个数
        • 替换:向指定位置插入任意数量的项,且同时删除任意数量的项,只需指定 3 个参数:起始位置,要删除的项数,要插入的任意数量的项
      var colors = ["red", "green", "blue"];
      var removed = colors.splice(0,1); 
      alert(colors); 		// green,blue 
      alert(removed); 	// red,返回的数组中只包含一项
      removed = colors.splice(1, 0, "yellow", "orange"); 
      alert(colors); 		// green,yellow,orange,blue 
      alert(removed); 	// 返回的是一个空数组
      removed = colors.splice(1, 1, "red", "purple"); 
      alert(colors); 		// green,red,purple,orange,blue 
      alert(removed); 	// yellow,返回的数组中只包含一项
      
    9. 位置方法

      • indexOf():从数组的开头(索引位置0)开始向后查找
      • lastIndexOf():从数组的末尾开始向前查找
      var numbers = [1,2,3,4,5,4,3,2,1];
      numbers.indexOf(4);		    // 3
      numbers.lastIndexOf(4);		// 5
      numbers.indexOf(4,4);		// 5
      numbers.lastIndexOf(4,4);	// 3
      var person = {name:"mjj"};
      var people = [{name:'mjj'}];
      var morePeople = [person];
      people.indexOf(person); 	 // -1
      morePeople.indexOf(person);  // 0
      
    10. 迭代方法

      • filter():利用指定的函数确定是否在返回的数组中包含某一项
      var numbers = [1,2,3,4,5,4,3,2,1];
      var filterResult = numbers.filter(function(item, index, array){
          return (item > 2);
      });
      alert(filterResult); 	// [3,4,5,4,3]
      
      • map():返回一个数组,而这个数组的每一项都是在原始数组中的对应项上执行函数的结果
      var numbers = [1,2,3,4,5,4,3,2,1];
      var filterResult = numbers.map(function(item, index, array){
          return item * 2;
      });
      alert(filterResult); 	// [2,4,6,8,10,8,6,4,2]
      
      • forEach():对数组中的每一项执行函数,没有返回值,本质上与使用for循环迭代数组一样,只能在数组中使用
      //执行某些操作,相当于for循环
      var numbers = [1,2,3,4,5,4,3,2,1];
      numbers.forEach(function(item, index, array){
      });
      

    2.2 字符串:String

    1. 字符串的创建方式

      var stringValue = "hello world"; 
      
    2. length属性

      var stringValue = "hello world"; 
      alert(stringValue.length);            // "11"
      
    3. 字符方法

      • charAt():返回给定位置的那个字符
      var stringValue = "hello world"; 
      alert(stringValue.charAt(1));         // "e"
      
      • charCodeAt():返回给定位置的那个字符所对应的编码
      var stringValue = "hello world";
      alert(stringValue.charCodeAt(1));     // 输出"101"
      
    4. 字符操作方法

      • concat():用于将一或多个字符串拼接起来,返回拼接得到的新字符串
      • +或${},也可以拼接字符串
      var stringValue = "hello ";
      var result = stringValue.concat("world"); alert(result);           // "hello world" 
      alert(stringValue);      // "hello"
      
      // concat()方法可以接受任意多个参数,也就是说可以通过它来拼接任意多个字符串
      var stringValue = "hello ";
      var result = stringValue.concat("world", "!");
      alert(result);           // "hello world!"
      
      // 拼接字符串
      // 通用方式:
      var name = 'wusir', age = 28;
      var str = name + '今年是' + age + '岁了,快要结婚了,娶了个黑姑娘';
      // es6的模板字符串,使用``(Tab上面的那个键)
      var str2 = `${name}今年是${age}岁了,快要结婚了,娶了个黑姑娘`;
      
      • slice(),substr(),substring():基于子字符串创建新字符串的方法
      var stringValue = "hello world";
      // 正值情况下
      stringValue.slice(3);          // "lo world"
      stringValue.substring(3);      // "lo world"
      stringValue.substr(3));        // "lo world"
      stringValue.slice(3, 7);       // "lo w"
      stringValue.substring(3,7);    // "lo w"
      stringValue.substr(3, 7);      // "lo worl
      // 负值情况下
      stringValue.slice(-3);         // "rld" 
      stringValue.substring(-3);     // "hello world"
      stringValue.substr(-3);        // "rld"
      stringValue.slice(3, -4);      // "lo w" 
      stringValue.substring(3, -4);  // "hel"
      stringValue.substr(3, -4);     // ""(空字符串)
      
    5. 字符串位置方法

      • indexOf():从字符串的开头向后搜索子字符串
      • lastIndexOf():从字符串的末尾向前搜索子字符串
      var stringValue = "hello world";
      alert(stringValue.indexOf("o"));            // 4
      alert(stringValue.lastIndexOf("o"));        // 7
      alert(stringValue.indexOf("o", 6));         // 7
      alert(stringValue.lastIndexOf("o", 6));     // 4
      
    6. trim():删除字符串的前后空格

      var stringValue = "   hello world   ";
      stringValue.trim();       // "hello world"
      
    7. 字符串大小写转换方法

      • toUpperCase():小写转换成大写
      • toLowerCase():大写转换成小写
      var stringValue = "hello world";
      stringValue.toUpperCase();       // "HELLO WORLD"
      stringValue.toLowerCase();       // "hello world"
      

    2.3 日期对象:Date

    1. 日期对象的创建方式

      var myDate = new Date();
      
    2. 基本方法

      • getDate():返回指定日期对象的月份中的第几天
      • Date():返回当天的日期和时间
      • getMonth():返回指定日期对象的月份
      • getFullYear():返回指定日期对象的年份
      • getDay():返回指定日期对象的星期中的第几天
      • getHours():返回指定日期对象的小时
      • getMinutes():返回指定日期对象的分钟
      • getSeconds():返回指定日期对象的秒数
    3. 日期格式化方法

      • toLocaleString():以特定于实现的格式显示年月日,时分秒;
      • toDateString():以特定于实现的格式显示星期几、月、日和年
      • toTimeString():以特定于实现的格式显示时、分、秒和时区;
      • toUTCString():以特定于实现的格式完整的 UTC 日期
      var myDate = new Date();
      myDate.toLocaleString();    	// "2019/6/4 上午9:33:58"
      myDate.toDateString();          // "Mon Apr 15 2019"
      myDate.toTimeString();          // "10:11:53 GMT+0800 (中国标准时间)"
      myDate.toUTCString();		   // "Mon, 15 Apr 2019 02:11:53 GMT"
      
    4. 将今天的星期数显示在网页上,即写入body中,使用document.write

      var weeks = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
      console.log(weeks[date.getDay()]);
      var day = weeks[date.getDay()];
      document.write(`<a href="#">${day}</a>`);
      
    5. 数字时钟

      • 示例:返回了用数字时钟格式的时间
      var time = new Date();
      var hour = time.getHours();
      var minute = time.getMinutes();
      var second = time.getSeconds();
      var temp = "" + ((hour > 12) ? hour - 12 : hour);
      if (hour == 0)
          temp = "12";
      temp += ((minute < 10) ? ":0" : ":") + minute;
      temp += ((second < 10) ? ":0" : ":") + second;
      temp += (hour >= 12) ? " P.M." : " A.M.";
      alert(temp);
      
      • 升级版:在网页上显示数字时钟的动态效果
      <body>
      <h2 id="time"></h2>
      <script>
          var timeObj = document.getElementById('time');
          console.log(time);
          function getNowTime() {
              var time = new Date();
              var hour = time.getHours();
              var minute = time.getMinutes();
              var second = time.getSeconds();
              var temp = "" + ((hour > 12) ? hour - 12 : hour);
              if (hour == 0) {
                  temp = "12";
              }
              temp += ((minute < 10) ? ":0" : ":") + minute;
              temp += ((second < 10) ? ":0" : ":") + second;
              temp += (hour >= 12) ? " P.M." : " A.M.";
              timeObj.innerText = temp;
          }
          setInterval(getNowTime, 20)
      </script>
      </body>
      

    2.4 数学对象:Math

    1. min()和max()方法

      • Math.min():求最小值
      • Math.max():求最大值
      var max = Math.max(3, 54, 32, 16);
      alert(max);    // 54
      var min = Math.min(3, 54, 32, 16);
      alert(min);    // 3
      
      // 特殊:使用apply,找到数组中最大或最小值
      var values = [1,2,36,23,43,3,41];
      var max = Math.max.apply(null, values);
      
    2. 舍入方法

      • Math.ceil():天花板函数,只入不舍,相当于取整再加1
        • 执行向上舍入,即它总是将数值向上舍入为最接近的整数
      • Math.floor():地板函数,只舍不入,相当于取整
        • 执行向下舍入,即它总是将数值向下舍入为最接近的整数
      • Math.round():四舍五入,和数学中的取舍方式一致
        • 执行标准舍入,即它总是将数值四舍五入为最接近的整数
      var num = 25.7;
      var num2 = 25.2;
      Math.ceil(num);     // 26
      Math.floor(num);    // 25
      Math.round(num);    // 26
      Math.round(num2);   // 25
      
    3. random()方法

      • 用来取随机数
      • Math.random():方法返回大于等于0小于1的一个随机数
      // 例1:获取min到max的范围的整数
      function random(lower, upper) {
          return Math.floor(Math.random() * (upper - lower)) + lower;
      }
      
      // 例2: 获取随机颜色
      /* 产生一个随机的rgb颜色
      @return {String}  返回颜色rgb值字符串内容,如:rgb(201, 57, 96) */
      function randomColor() {
      	// 随机生成rgb值,每个颜色值在0-255之间
          var r = random(0, 256),
              g = random(0, 256),
              b = random(0, 256);
      	// 连接字符串的结果
          var result = "rgb("+ r +","+ g +","+ b +")";
          // 返回结果
          return result;
      }
      
      // 例3: 获取随机验证码
      function createCode(){
          //首先默认code为空字符串
          var code = '';
          //设置长度,这里看需求,我这里设置了4
          var codeLength = 4;
          //设置随机字符
          var random = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z'];
          //循环codeLength 我设置的4就是循环4次
          for(var i = 0; i < codeLength; i++){
              //设置随机数范围,这设置为0 ~ 36
              var index = Math.floor(Math.random()*36);
              //字符串拼接 将每次随机的字符 进行拼接
              code += random[index]; 
          }
          //将拼接好的字符串赋值给展示的Value
          return code
      }
      

    三、字符串和数值之间的转换

    1. 字符串转数值

      • parseInt():字符串转整数
      • perseFloat():字符串转浮点型
      • Number():字符串转数值
      var str = '123.0000111';			
      console.log(parseInt(str));			 // 123
      console.log(typeof parseInt(str));	  // number
      console.log(parseFloat(str));		 // 123.0000111
      console.log(typeof parseFloat(str));  // number
      console.log(Number(str));			 // 123.0000111
      
    2. 数值转字符串

      • toString():数值转字符串
      • 数字+空的字符串:数值转字符串
      var num  = 1233.006;
      // 强制类型转换
      console.log(String(num));
      console.log(num.toString());
      // 隐式转换
      console.log(''.concat(num));
      // toFixed()方法会按照指定的小数位返回数值的字符串 四舍五入
      console.log(num.toFixed(2));
      
  • 相关阅读:
    数据不平衡
    2D到3D 外参矩阵估计
    ppt 绘图转成 Latex 常用的 eps 格式
    3D 旋转中 旋转矩阵 欧拉角 四元数的相互转换
    opencv使用 --- fastGlobalSmootherFilter
    Pytorch
    MTCNN 复现
    3DFace基础---光照估计
    Pytorch --- cuda 相关
    Pytorch---多维数组运算过程的索引处理
  • 原文地址:https://www.cnblogs.com/zengyi1995/p/11040877.html
Copyright © 2011-2022 走看看