找回密码
 立即注册
首页 业界区 安全 前端三剑客——javascript内置对象与其方法 ...

前端三剑客——javascript内置对象与其方法

殳世英 昨天 13:10
大纲:
  1.对象创建的常用3种方法
       引用/新增属性方法
  2.内置对象及其常见方法
      Number
      Math
      Date
      String
 
      Array
      对象与数组的解包操作以及在函数中的运用
      JSON
      console
 
 
对象创建的方法
  对象创建的常用三种方法
  1.     //方法一   直接创建有属性和方法的对象
  2.     var Person={
  3.         name:"guohan",
  4.         age:22,
  5.         say(){
  6.             console.log(Person.name);
  7.         }
  8.     }
  9.     //引用属性和方法
  10.     console.log(Person.name);
  11.     Person.say();
  12.     //新增属性和方法
  13.     Person["hobby1"]="睡觉";
  14.     Person.hobby2="打球";
  15.     Person.call=function(){
  16.         console.log(this.hobby1);       //如果是箭头函数则this指向父级作用域的this是window
  17.     }
  18.     Person.call();
复制代码
  1. //方法二创建函数后实例对象
  2. function Person(name,age){
  3.     this.name=name;
  4.     this.age=age;
  5.     this.say=()=>{
  6.         console.log(this.age);
  7.     }
  8. }
  9. //实例化对象和引用属性和方法
  10. var man = new Person("guohan",22);
  11. console.log(man.name);
  12. man.say();
  13. //新增属性和方法
  14. man.call=function (){
  15.     console.log(man.age);
  16. }
  17. man.call();
复制代码
  1. //方法三创建类后实例类的对象
  2. class Person{
  3.     constructor(name,age){
  4.         this.name=name;
  5.         this.age=age;
  6.     }
  7.     say(){
  8.         console.log(this.age);
  9.     }
  10. }
  11. //实例化对象和引用属性和方法
  12. var man = new Person("guohan",22);
  13. console.log(man.name);
  14. man.say();
  15. //新增属性和方法
  16. man.call=function(){
  17.     console.log(man.age);
  18. }
  19. man.call();
复制代码
 
内置对象及其方法
1.png

   Number  数值对象
toFixed(n ):保留n个小数位
  1. var num = 3.14;
  2. console.log(num.toFixed());     //3
  3. console.log(num.toFixed(1));    //3.1
  4. console.log(num.toFixed(3));    //3.140
复制代码
   Math    数学对象
Math.round(num)   对num进行四舍五入!取整!
  1. //Math.round(num)   对num进行四舍五入!取整!
  2. console.log(Math.round(3.145));     //3
  3. //与python区别
  4. /**
  5. *     num = 10.346
  6. *     print(round(num,2))          //10.35
  7. */
复制代码
Math.ceil(nun)    对num进行向上取整  进一法取整
  1. //Math.ceil(nun)    对num进行向上取整  进一法取整
  2. console.log(Math.ceil(2.1));        //3
复制代码
 Math.floor(num)   向下取整:保留整数部分去除小数部分
  1. //Math.floor(num)   向下取整:保留整数部分去除小数部分
  2. console.log(Math.floor(3.64));      //3
复制代码
 Math.random()     获取[0,1)之间的随机数
  1. //Math.random()     获取[0,1)之间的随机数
  2. console.log(Math.random().toFixed(2));              //0.36
  3. //Math.random()*100     获取[0,100)之间的随机数
  4. console.log((Math.random()*100).toFixed(2));        //45.84
  5. //parseInt(Math.random()*100)     获取[0,100)之间的随机数整数
  6. console.log(parseInt((Math.random() * 100).toFixed(2)));    //26
  7. //随机返回指定范围的整数
  8. var ret = (min,max)=>parseInt(Math.random()*(max-min))+min;
  9. /*
  10. function ret(min,max){
  11.      return parseInt(Math.random()*(max-min))+min;
  12. }
  13. */
  14. console.log(ret(20,40));
复制代码
    Date    时间对象
/**
 * 创建Date时间对象:         var t = new Date();
 * 获取系统本地时间:          console.log(t);
 * 获取年份:                t.getFullYear();
 * 获取月份(0-11):          t.getMonth()+1;
 * 获取几号(1-31):          t.getDate();
 * 获取星期几(0-6):          t.getDay();
 * 获取小时:                t.getHours();
 * 获取分钟:                t.getMinutes();
 * 获取秒数:                t.getSeconds();
 * 获取时间戳:              t.getTime();
 * 获取JSON格式时间:         t.toJSON();
 * @type {Date}
 */
  1. //Date时间对象及其方法
  2. /**
  3. * 创建Date时间对象:         var t = new Date();
  4. * 获取系统本地时间:          console.log(t);
  5. * 获取年份:                t.getFullYear();
  6. * 获取月份(0-11):          t.getMonth()+1;
  7. * 获取几号(1-31):          t.getDate();
  8. * 获取星期几(0-6):          t.getDay();
  9. * 获取小时:                t.getHours();
  10. * 获取分钟:                t.getMinutes();
  11. * 获取秒数:                t.getSeconds();
  12. * 获取时间戳:              t.getTime();
  13. * 获取JSON格式时间:         t.toJSON();
  14. * @type {Date}
  15. */
  16. var t = new Date();
  17. //实例化时间对象new Date():  获取系统本地时间
  18. console.log(t);                                 //Sun Nov 02 2025 21:37:22 GMT+0800 (中国标准时间)
  19. //对象.getFullYear():  获取年份
  20. console.log(t.getFullYear());                   //2025
  21. //对象.getMonth():  获取月份(0-11)  0:11月  要加一
  22. console.log(t.getMonth()+1);
  23. //对象.getDate():  获取几号(1-31)
  24. console.log(t.getDate());                       //2
  25. //对象.getDay():  获取星期几(0-6)  0:星期天
  26. console.log(t.getDay());                        //0
  27. //对象.getHours():  获取小时
  28. console.log(t.getHours());                      //22
  29. //对象.getMinutes():  获取分钟
  30. console.log(t.getMinutes());                    //6
  31. //对象.getSeconds():  获取秒
  32. console.log(t.getSeconds());                    //40
  33. //获取时间戳1970-1-1
  34. console.log(t.getTime());                       //1762092410769
  35. //对象.toJSON():  以JSON数据格式返回时间字符串
  36. console.log(t.toJSON(),typeof t.toJSON() );                        //2025-11-02T14:10:53.322Z string
  37. //补0:比如分钟为10以内时显示:08
  38. // function cramZero(param){
  39. //     if(String(param).length<2){
  40. //         param = '0'+param;
  41. //         return param;
  42. //     }
  43. //     return param;
  44. // }
  45. var cramZero = (param) => String(param).length<2?'0'+param:param;
  46. ret = `${t.getFullYear()}-${cramZero(t.getMonth()+1)}-${cramZero(t.getDate())}-${cramZero(t.getHours())}-${cramZero(t.getMinutes())}-${cramZero(t.getSeconds())}`;
  47. console.log(ret);
复制代码
  1. //String字符串对象及其方法
  2. /**
  3. * var s = "guohan";
  4. * 拼接2个或者多个字符:                  s.concat(str);
  5. *将Unicode编码值转成对应字符:            s.fromCharCode(num)
  6. *返回指定字符首次的索引位置:               s.indexOf()
  7. * 判断是否以某个字符开头结尾:              s.startsWith/endsWith()
  8. * 判断是否包含某字符串:                  s.includes()
  9. * 获取字符串切片(支持负数索引):            s.slice(start,end)
  10. * 获取字符串切片:                         s.subString(start,end)
  11. * 获取指定长度字符串切片:                 s.str(start,len)
  12. *变大写/小写:                           s.toUpperCase/toLowerCase()
  13. * 去空白:                              s.trim()
  14. *分割:                                 s.split(指定字符)
  15. *替换一次/全部替换:                       s.replace/replaceAll()
  16. *search()
  17. *match()
  18. * @type {string}
  19. */
复制代码
    对象与数组的解包操作以及在函数中的运用    
      数组解包
  1. //String字符串对象及其方法
  2. /**
  3. * var s = "guohan";
  4. * 拼接2个或者多个字符:                  s.concat(str);
  5. *将Unicode编码值转成对应字符:            s.fromCharCode(num)
  6. *返回指定字符首次的索引位置:               s.indexOf()
  7. * 判断是否以某个字符开头结尾:              s.startsWith/endsWith()
  8. * 判断是否包含某字符串:                  s.includes()
  9. * 获取字符串切片(支持负数索引):            s.slice(start,end)
  10. * 获取字符串切片:                         s.subString(start,end)
  11. * 获取指定长度字符串切片:                 s.str(start,len)
  12. *变大写/小写:                           s.toUpperCase/toLowerCase()
  13. * 去空白:                              s.trim()
  14. *分割:                                 s.split(指定字符)
  15. *替换一次/全部替换:                       s.replace/replaceAll()
  16. *search()
  17. *match()
  18. * @type {string}
  19. */
  20. var s = "guo";
  21. //对象.concat(字符串):  字符串拼接拼接2个或更多个
  22. console.log(s.concat("han"));           //guohan
  23. //对象.fromCharCode():  将一个或者多个Unicode编码值装换成对应的字符     相当于py中chr
  24.     //py:   print(chr(65))
  25. console.log(String.fromCharCode(65));       //A
  26. //对象.indexOf(字符):  返回指定的字符在字符串中首次出现的位置
  27. console.log(s.indexOf('o'));                //2
  28. //对象.startsWith(字符):  判断是否以某个字符开头
  29. console.log(s.startsWith('s'));             //false
  30. //对象.endsWith(字符):  判断是否以某个字符结束
  31. console.log(s.endsWith('o'));               //true
  32. //对象.includes(字符):  判断是否包含某个字符串
  33. console.log(s.includes('uo'));              //true
  34. //对象.slice(开始下标,结束下标):  [start,end) 获取指定位置的切片支持负数索引
  35. console.log(s.slice(0, -1));                //gu
  36. //对象.subString(开始下标,结束下标):  [start,end) 获取指定位置的切片
  37. console.log(s.substring(0, 2));             //gu
  38. //对象.substr(开始下标,截取长度):  [start,len] 获取从指定索引位置获取指定数目的字符
  39. console.log(s.substr(0, 2));                //gu
  40. //对象.toUpperCase():  将字符串变成大写
  41. console.log(s.toUpperCase());               //GUO
  42. //对象.toLowerCase():  将字符串变成小写
  43. console.log(s.toLowerCase());               //guo
  44. ///对象.trim():  去除字符串两边空白
  45. console.log(s.trim());
  46. //以指定字符分割成数组
  47. console.log(s.split(""));                   //['g', 'u', 'o']
  48. //替换一次
  49. console.log(s.replace("g", "h"));           //huo
  50.     //py:默认全部替换,后加次数可指定替换次数
  51. //全部替换
  52. console.log(s.replaceAll("g", "h"));
  53. //search()
  54. //match()
复制代码
      对象解包
  1. //Array
  2. /**
  3. * var num=["guohan","gh","gg","hh"]
  4. * 增删改查
  5. *  增:
  6. * 头部增加:                        array.unshift(value)
  7. * 尾部增加:                         array.push(value)
  8. * 指定位置增加:                      array.splice(index,0,value)
  9. *
  10. * 删:
  11. * 头部删除:                          array.shift()
  12. * 尾部删除:                         array.pop()
  13. * 指定位置删除:                      array.splice(index,number)
  14. *
  15. * 改:                               array.splice(index,1,value)
  16. *
  17. * 查:
  18. *      下标
  19. * 查某个成员下标:                  array.indexOf(value)
  20. * 循环数组成员下标:                for(var index in array){console.log(index)}
  21. *      值
  22. * 查指定索引位置元素:               array[index]
  23. * 切片(左闭右开)支持负索引:          array.slice(star,end)
  24. * 循环数组所有成员:                for(var value of array){console.log(value)}
  25. * forEach函数查数组成员/下标:       array.forEach((value,index,array)=>{console.log(value,index,array})
  26. *      判断
  27. * 判断指定元素是否包含于数组:         array.includes(value)
  28. * 判断指定元素是否是数组:             Array.isArray(value)
  29. * 判断数组成员是否均满足条件:          array.every(func)
  30. * 判断数组成员是否至少有一个满足条件:     array,some(func)
  31. *
  32. *
  33. * 顺序相关
  34. * 反转:                          array.reverse()
  35. * 按ascii码值进行排序:             array.sort()
  36. *
  37. * 拼接
  38. * 数组拼接:                        array.concat(new_array)
  39. * 数组按指定字符拼接成字符串:          array.join(str)
  40. *
  41. * 高级函数方法对数组进行操作
  42. * 通过指定函数对数组每个成员进行处理:     array.map(函数)
  43. * 通过指定函数对数组每个成员进行筛选:     array.filter(函数)
  44. * 通过指定函数对数组成员进行累计:         array.reduce(函数)
  45. *
  46. *
  47. * @type {string[]}
  48. */
复制代码
      解包在函数中的运用
  1. //Array
  2. /**
  3. * var num=["guohan","gh","gg","hh"]
  4. * 增删改查
  5. *  增:
  6. * 头部增加:                        array.unshift(value)
  7. * 尾部增加:                         array.push(value)
  8. * 指定位置增加:                      array.splice(index,0,value)
  9. *
  10. * 删:
  11. * 头部删除:                          array.shift()
  12. * 尾部删除:                         array.pop()
  13. * 指定位置删除:                      array.splice(index,number)
  14. *
  15. * 改:                               array.splice(index,1,value)
  16. *
  17. * 查:
  18. *      下标
  19. * 查某个成员下标:                  array.indexOf(value)
  20. * 循环数组成员下标:                for(var index in array){console.log(index)}
  21. *      值
  22. * 查指定索引位置元素:               array[index]
  23. * 切片(左闭右开)支持负索引:          array.slice(star,end)
  24. * 循环数组所有成员:                for(var value of array){console.log(value)}
  25. * forEach函数查数组成员/下标:       array.forEach((value,index,array)=>{console.log(value,index,array})
  26. *      判断
  27. * 判断指定元素是否包含于数组:         array.includes(value)
  28. * 判断指定元素是否是数组:             Array.isArray(value)
  29. * 判断数组成员是否均满足条件:          array.every(func)
  30. * 判断数组成员是否至少有一个满足条件:     array,some(func)
  31. *
  32. *
  33. * 顺序相关
  34. * 反转:                          array.reverse()
  35. * 按ascii码值进行排序:             array.sort()
  36. *
  37. * 拼接
  38. * 数组拼接:                        array.concat(new_array)
  39. * 数组按指定字符拼接成字符串:          array.join(str)
  40. *
  41. * 高级函数方法对数组进行操作
  42. * 通过指定函数对数组每个成员进行处理:     array.map(函数)
  43. * 通过指定函数对数组每个成员进行筛选:     array.filter(函数)
  44. * 通过指定函数对数组成员进行累计:         array.reduce(函数)
  45. *
  46. *
  47. * @type {string[]}
  48. */
  49. var num=["guohan","gh","gg","hh"];
  50. //对象.concat(数组)
  51. console.log(num.concat([1, 2, 3]),num.concat([1, 2, 3]).length);     //['guohan', 'gh', 'gg', 'hh', 1, 2, 3]
  52. //增加
  53. //对象.push():    尾部增加
  54. num.push("h")
  55. console.log(num);               //['guohan', 'gh', 'gg', 'hh', 'h']
  56. //对象.unshift():     头部增加
  57. num.unshift("h");
  58. console.log(num);               //['h', 'guohan', 'gh', 'gg', 'hh', 'h']
  59.         //删除
  60. //对象.pop():     尾部删除
  61. num.pop();
  62. console.log(num);               //['h', 'guohan', 'gh', 'gg', 'hh']
  63. //对象.shift():    头部删除
  64. num.shift();
  65. console.log(num);               //['guohan', 'gh', 'gg', 'hh']
  66.         //指定位置增加删除和修改
  67. //对象.splice(索引,删除的元素个数,增加的元素1,增加的元素2)
  68.     //删除
  69. console.log(num.splice(1, 2));      //['gh', 'gg']
  70. console.log(num);                   //['guohan', 'hh']
  71.     //增加
  72. num.splice(1,0,222,333);
  73. console.log(num,num.length);        //['guohan', 222, 333, 'hh'] 4
  74.     //修改
  75. num.splice(1,1,"gh");
  76. console.log(num);                   //['guohan', 'gh', 333, 'hh']
  77. //指定数组成员返回索引
  78. console.log(num.indexOf("guohan"));     //0
  79. //判断指定成员是否在数组中
  80. console.log(num.includes("guohan"));    //true
  81. //对象.slice(start,end):  反回数组切片左闭右开
  82. console.log(num.slice(1,-1));           //[222, 333]
  83.         //对数组进行循环操作
  84. //for循环获取下标
  85. for(var data in num){
  86.     console.log(data);
  87. }
  88. //for循环获取成员
  89. for(var data of num){
  90.     console.log(data);
  91. }
  92. //对象.forEach((值,索引,数组本身)=>{代码})
  93. num.forEach((value,index,array)=>{
  94.     console.log(value,index,array);
  95. })
  96. //反转数组顺序
  97. num.reverse();
  98. console.log(num);       //['hh', 333, 'gh', 'guohan']
  99. //对象.sort():    根据ascii码值进行排序
  100. console.log(num.sort());
  101. //以指定字符对数组进行拼接得到字符串
  102. console.log(num.join(""));      //333ghguohanhh
  103.         //案例:对字符串进行反转
  104. function strrev(str){
  105.     ret = str.split("").reverse().join("")
  106.     return ret;
  107. }
  108. console.log(strrev("guohan"));      //333ghguohanhh
  109. //Array.isArray(对象):  判断指定对象是不是数组
  110. console.log(Array.isArray(num));    //true
  111. //[333, 'gh', 'guohan', 'hh']
  112.         //高级方法
  113. //对象.map(指定函数):     通过指定函数对数组每个成员进行处理
  114. console.log(num.map((value) => typeof (value) === 'number' ? value + 1 : value));       //[334, 'gh', 'guohan', 'hh']
  115. console.log(num.map(function (value) {
  116.     if (typeof (value) === 'number') {
  117.         return value += 1;
  118.     }else{
  119.         return value;
  120.     }
  121. }));                                                                                    //[334, 'gh', 'guohan', 'hh']
  122. //对象.filter(筛选函数):      通过指定函数对数组成员进行筛选
  123. console.log(num.filter((value) => typeof (value) === 'string' ? value : null));         //['gh', 'guohan', 'hh']
  124. console.log(num.filter((value) => typeof (value) === 'number' ? value : null));         //333]
  125. console.log(num.filter(function (value) {
  126.     if (typeof (value) === 'number') {
  127.         return value;
  128.     } else {
  129.         return null;
  130.     }
  131. }));                                                                                    //333]
  132. //对象.reduce(函数(参数1,参数2)):       通过指定函数对数组成员进行累计操作
  133. console.log(num.reduce((value1, value2) => {
  134.     return value1 + value2;
  135. }));                                                                                    //333ghguohanhh
  136. /**
  137. * python中内置函数
  138. * import functools
  139. * content = [1,22,44,"gouhan","gh"]
  140. *
  141. * #内置函数map
  142. * result1 = list(map(lambda x:x+2 if isinstance(x,int) else x,content))
  143. * print(result1)       [3, 24, 46, 'gouhan', 'gh']
  144. *
  145. * #内置函数filter
  146. * result2 = list(filter(lambda x: isinstance(x,int),content))
  147. * print(result2)       [1, 22, 44]
  148. *
  149. * #内置函数reduce
  150. * result3 = functools.reduce(lambda x,y:x+y if isinstance(x and y,int) else str(x)+y,content)
  151. * print(result3)       67gouhangh
  152. */
  153. //[333, 'gh', 'guohan', 'hh']
  154. //对象.every(函数): 判断数组成员是否均满足条件,
  155. console.log(num.every((value) => {
  156.     return typeof value === 'string';
  157. }));                                //false
  158. //判断数组成员是否至少有一个满足条件
  159. console.log(num.some((value) => {
  160.     return typeof value === 'string';
  161. }));                                //true
复制代码
    JSON
  1. //数组解包
  2. var array = [1,2,3,4];
  3. //全接受
  4. var  [num1,num2,num3,num4] = array;
  5. console.log(num1,num2,num3,num4);           //1 2 3 4
  6. //顺序接收:部分接收
  7. var [number1, ,number2] = array;
  8. console.log(number1,number2);               //1 3
  9. //顺序接收:接收剩余数据
  10. var [data1,data2,...args] = array;
  11. console.log(args);                          //[3, 4]
复制代码
  1. //数组解包
  2. var array = [1,2,3,4];
  3. //全接受
  4. var  [num1,num2,num3,num4] = array;
  5. console.log(num1,num2,num3,num4);           //1 2 3 4
  6. //顺序接收:部分接收
  7. var [number1, ,number2] = array;
  8. console.log(number1,number2);               //1 3
  9. //顺序接收:接收剩余数据
  10. var [data1,data2,...args] = array;
  11. console.log(args);                          //[3, 4]//JSON.stringify(obj):  把对象转成JSON格式的字符串var obj = {name:"gh",age:22};console.log(JSON.stringify(obj));           //{"name":"gh","age":22}//JSON.parse(str):      把符合JSON语法的字符串转换成js对象var obj2 = '{"name":"gh","age":22}';console.log(JSON.parse(obj2));              //Object:  {name: 'gh', age: 22}//与python区别/*"""#import json#json.dumps(obj):   把python中对象转成JSON格式字符串#jspn.dumps(obj,ensure_ascii=False):    对象中有中文时序列化#json.loads(str):   把json格式字符串转成python对象python中set datetime类型不可以转成json格式的字符串python中元组序列化转成[]    反序列化时得到列表"""import jsoninfo = {'name':'guohan','age':22}#把python中对象转成json格式字符串print(json.dumps(info))                         #{"name": "guohan", "age": 22}#python对象中有中文时序列化info = {'name':'郭晗','age':22}print(json.dumps(info,ensure_ascii=False))      #{"name": "郭晗", "age": 22}#把json格式字符串转成python对象content = '{"name": "guohan", "age": 22}'print(json.loads(content))                      #{'name': 'guohan', 'age': 22}content2 = '{"name": "郭晗", "age": 22}'print(json.loads(content2))                     #{'name': '郭晗', 'age': 22}#集合无法序列化info3 = {'guohan',22}try:    print(json.dumps(info3))except TypeError as e:    print("无法序列化")                          #无法序列化#元组序列化和反序列化data = (1,2,3)print(json.dumps(data))                         #[1, 2, 3]data2 = '[1, 2, 3]'print(json.loads(data2))                        #[1, 2, 3] */
复制代码
   console    控制台操作对象,浏览器中进行代码打印与调试
  1. //解包在函数中的运用
  2. //对象解包
  3. function func1({x,y}){
  4.     console.log(x+y);
  5. }
  6. func1({x:10,y:20});                          //30
  7. //数组解包
  8. function func2([x,y]){
  9.     console.log(x,y);
  10. }
  11. func2([1,2]);                                //1 2
  12. function func3([x,...args]){
  13.     console.log(args);
  14. }
  15. func3([1,2,3,4]);                            //[2, 3, 4]
复制代码
 
 
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册