大纲:
1.对象创建的常用3种方法
引用/新增属性方法
2.内置对象及其常见方法
Number
Math
Date
String
Array
对象与数组的解包操作以及在函数中的运用
JSON
console
对象创建的方法
对象创建的常用三种方法- //方法一 直接创建有属性和方法的对象
- var Person={
- name:"guohan",
- age:22,
- say(){
- console.log(Person.name);
- }
- }
- //引用属性和方法
- console.log(Person.name);
- Person.say();
- //新增属性和方法
- Person["hobby1"]="睡觉";
- Person.hobby2="打球";
- Person.call=function(){
- console.log(this.hobby1); //如果是箭头函数则this指向父级作用域的this是window
- }
- Person.call();
复制代码- //方法二创建函数后实例对象
- function Person(name,age){
- this.name=name;
- this.age=age;
- this.say=()=>{
- console.log(this.age);
- }
- }
- //实例化对象和引用属性和方法
- var man = new Person("guohan",22);
- console.log(man.name);
- man.say();
- //新增属性和方法
- man.call=function (){
- console.log(man.age);
- }
- man.call();
复制代码- //方法三创建类后实例类的对象
- class Person{
- constructor(name,age){
- this.name=name;
- this.age=age;
- }
- say(){
- console.log(this.age);
- }
- }
- //实例化对象和引用属性和方法
- var man = new Person("guohan",22);
- console.log(man.name);
- man.say();
- //新增属性和方法
- man.call=function(){
- console.log(man.age);
- }
- man.call();
复制代码
内置对象及其方法
Number 数值对象
toFixed(n ):保留n个小数位- var num = 3.14;
- console.log(num.toFixed()); //3
- console.log(num.toFixed(1)); //3.1
- console.log(num.toFixed(3)); //3.140
复制代码 Math 数学对象
Math.round(num) 对num进行四舍五入!取整!- //Math.round(num) 对num进行四舍五入!取整!
- console.log(Math.round(3.145)); //3
- //与python区别
- /**
- * num = 10.346
- * print(round(num,2)) //10.35
- */
复制代码 Math.ceil(nun) 对num进行向上取整 进一法取整- //Math.ceil(nun) 对num进行向上取整 进一法取整
- console.log(Math.ceil(2.1)); //3
复制代码 Math.floor(num) 向下取整:保留整数部分去除小数部分- //Math.floor(num) 向下取整:保留整数部分去除小数部分
- console.log(Math.floor(3.64)); //3
复制代码 Math.random() 获取[0,1)之间的随机数- //Math.random() 获取[0,1)之间的随机数
- console.log(Math.random().toFixed(2)); //0.36
- //Math.random()*100 获取[0,100)之间的随机数
- console.log((Math.random()*100).toFixed(2)); //45.84
- //parseInt(Math.random()*100) 获取[0,100)之间的随机数整数
- console.log(parseInt((Math.random() * 100).toFixed(2))); //26
- //随机返回指定范围的整数
- var ret = (min,max)=>parseInt(Math.random()*(max-min))+min;
- /*
- function ret(min,max){
- return parseInt(Math.random()*(max-min))+min;
- }
- */
- 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}
*/- //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}
- */
- var t = new Date();
- //实例化时间对象new Date(): 获取系统本地时间
- console.log(t); //Sun Nov 02 2025 21:37:22 GMT+0800 (中国标准时间)
- //对象.getFullYear(): 获取年份
- console.log(t.getFullYear()); //2025
- //对象.getMonth(): 获取月份(0-11) 0:11月 要加一
- console.log(t.getMonth()+1);
- //对象.getDate(): 获取几号(1-31)
- console.log(t.getDate()); //2
- //对象.getDay(): 获取星期几(0-6) 0:星期天
- console.log(t.getDay()); //0
- //对象.getHours(): 获取小时
- console.log(t.getHours()); //22
- //对象.getMinutes(): 获取分钟
- console.log(t.getMinutes()); //6
- //对象.getSeconds(): 获取秒
- console.log(t.getSeconds()); //40
- //获取时间戳1970-1-1
- console.log(t.getTime()); //1762092410769
- //对象.toJSON(): 以JSON数据格式返回时间字符串
- console.log(t.toJSON(),typeof t.toJSON() ); //2025-11-02T14:10:53.322Z string
- //补0:比如分钟为10以内时显示:08
- // function cramZero(param){
- // if(String(param).length<2){
- // param = '0'+param;
- // return param;
- // }
- // return param;
- // }
- var cramZero = (param) => String(param).length<2?'0'+param:param;
- ret = `${t.getFullYear()}-${cramZero(t.getMonth()+1)}-${cramZero(t.getDate())}-${cramZero(t.getHours())}-${cramZero(t.getMinutes())}-${cramZero(t.getSeconds())}`;
- console.log(ret);
复制代码- //String字符串对象及其方法
- /**
- * var s = "guohan";
- * 拼接2个或者多个字符: s.concat(str);
- *将Unicode编码值转成对应字符: s.fromCharCode(num)
- *返回指定字符首次的索引位置: s.indexOf()
- * 判断是否以某个字符开头结尾: s.startsWith/endsWith()
- * 判断是否包含某字符串: s.includes()
- * 获取字符串切片(支持负数索引): s.slice(start,end)
- * 获取字符串切片: s.subString(start,end)
- * 获取指定长度字符串切片: s.str(start,len)
- *变大写/小写: s.toUpperCase/toLowerCase()
- * 去空白: s.trim()
- *分割: s.split(指定字符)
- *替换一次/全部替换: s.replace/replaceAll()
- *search()
- *match()
- * @type {string}
- */
复制代码 对象与数组的解包操作以及在函数中的运用
数组解包- //String字符串对象及其方法
- /**
- * var s = "guohan";
- * 拼接2个或者多个字符: s.concat(str);
- *将Unicode编码值转成对应字符: s.fromCharCode(num)
- *返回指定字符首次的索引位置: s.indexOf()
- * 判断是否以某个字符开头结尾: s.startsWith/endsWith()
- * 判断是否包含某字符串: s.includes()
- * 获取字符串切片(支持负数索引): s.slice(start,end)
- * 获取字符串切片: s.subString(start,end)
- * 获取指定长度字符串切片: s.str(start,len)
- *变大写/小写: s.toUpperCase/toLowerCase()
- * 去空白: s.trim()
- *分割: s.split(指定字符)
- *替换一次/全部替换: s.replace/replaceAll()
- *search()
- *match()
- * @type {string}
- */
- var s = "guo";
- //对象.concat(字符串): 字符串拼接拼接2个或更多个
- console.log(s.concat("han")); //guohan
- //对象.fromCharCode(): 将一个或者多个Unicode编码值装换成对应的字符 相当于py中chr
- //py: print(chr(65))
- console.log(String.fromCharCode(65)); //A
- //对象.indexOf(字符): 返回指定的字符在字符串中首次出现的位置
- console.log(s.indexOf('o')); //2
- //对象.startsWith(字符): 判断是否以某个字符开头
- console.log(s.startsWith('s')); //false
- //对象.endsWith(字符): 判断是否以某个字符结束
- console.log(s.endsWith('o')); //true
- //对象.includes(字符): 判断是否包含某个字符串
- console.log(s.includes('uo')); //true
- //对象.slice(开始下标,结束下标): [start,end) 获取指定位置的切片支持负数索引
- console.log(s.slice(0, -1)); //gu
- //对象.subString(开始下标,结束下标): [start,end) 获取指定位置的切片
- console.log(s.substring(0, 2)); //gu
- //对象.substr(开始下标,截取长度): [start,len] 获取从指定索引位置获取指定数目的字符
- console.log(s.substr(0, 2)); //gu
- //对象.toUpperCase(): 将字符串变成大写
- console.log(s.toUpperCase()); //GUO
- //对象.toLowerCase(): 将字符串变成小写
- console.log(s.toLowerCase()); //guo
- ///对象.trim(): 去除字符串两边空白
- console.log(s.trim());
- //以指定字符分割成数组
- console.log(s.split("")); //['g', 'u', 'o']
- //替换一次
- console.log(s.replace("g", "h")); //huo
- //py:默认全部替换,后加次数可指定替换次数
- //全部替换
- console.log(s.replaceAll("g", "h"));
- //search()
- //match()
复制代码 对象解包- //Array
- /**
- * var num=["guohan","gh","gg","hh"]
- * 增删改查
- * 增:
- * 头部增加: array.unshift(value)
- * 尾部增加: array.push(value)
- * 指定位置增加: array.splice(index,0,value)
- *
- * 删:
- * 头部删除: array.shift()
- * 尾部删除: array.pop()
- * 指定位置删除: array.splice(index,number)
- *
- * 改: array.splice(index,1,value)
- *
- * 查:
- * 下标
- * 查某个成员下标: array.indexOf(value)
- * 循环数组成员下标: for(var index in array){console.log(index)}
- * 值
- * 查指定索引位置元素: array[index]
- * 切片(左闭右开)支持负索引: array.slice(star,end)
- * 循环数组所有成员: for(var value of array){console.log(value)}
- * forEach函数查数组成员/下标: array.forEach((value,index,array)=>{console.log(value,index,array})
- * 判断
- * 判断指定元素是否包含于数组: array.includes(value)
- * 判断指定元素是否是数组: Array.isArray(value)
- * 判断数组成员是否均满足条件: array.every(func)
- * 判断数组成员是否至少有一个满足条件: array,some(func)
- *
- *
- * 顺序相关
- * 反转: array.reverse()
- * 按ascii码值进行排序: array.sort()
- *
- * 拼接
- * 数组拼接: array.concat(new_array)
- * 数组按指定字符拼接成字符串: array.join(str)
- *
- * 高级函数方法对数组进行操作
- * 通过指定函数对数组每个成员进行处理: array.map(函数)
- * 通过指定函数对数组每个成员进行筛选: array.filter(函数)
- * 通过指定函数对数组成员进行累计: array.reduce(函数)
- *
- *
- * @type {string[]}
- */
复制代码 解包在函数中的运用- //Array
- /**
- * var num=["guohan","gh","gg","hh"]
- * 增删改查
- * 增:
- * 头部增加: array.unshift(value)
- * 尾部增加: array.push(value)
- * 指定位置增加: array.splice(index,0,value)
- *
- * 删:
- * 头部删除: array.shift()
- * 尾部删除: array.pop()
- * 指定位置删除: array.splice(index,number)
- *
- * 改: array.splice(index,1,value)
- *
- * 查:
- * 下标
- * 查某个成员下标: array.indexOf(value)
- * 循环数组成员下标: for(var index in array){console.log(index)}
- * 值
- * 查指定索引位置元素: array[index]
- * 切片(左闭右开)支持负索引: array.slice(star,end)
- * 循环数组所有成员: for(var value of array){console.log(value)}
- * forEach函数查数组成员/下标: array.forEach((value,index,array)=>{console.log(value,index,array})
- * 判断
- * 判断指定元素是否包含于数组: array.includes(value)
- * 判断指定元素是否是数组: Array.isArray(value)
- * 判断数组成员是否均满足条件: array.every(func)
- * 判断数组成员是否至少有一个满足条件: array,some(func)
- *
- *
- * 顺序相关
- * 反转: array.reverse()
- * 按ascii码值进行排序: array.sort()
- *
- * 拼接
- * 数组拼接: array.concat(new_array)
- * 数组按指定字符拼接成字符串: array.join(str)
- *
- * 高级函数方法对数组进行操作
- * 通过指定函数对数组每个成员进行处理: array.map(函数)
- * 通过指定函数对数组每个成员进行筛选: array.filter(函数)
- * 通过指定函数对数组成员进行累计: array.reduce(函数)
- *
- *
- * @type {string[]}
- */
- var num=["guohan","gh","gg","hh"];
- //对象.concat(数组)
- console.log(num.concat([1, 2, 3]),num.concat([1, 2, 3]).length); //['guohan', 'gh', 'gg', 'hh', 1, 2, 3]
- //增加
- //对象.push(): 尾部增加
- num.push("h")
- console.log(num); //['guohan', 'gh', 'gg', 'hh', 'h']
- //对象.unshift(): 头部增加
- num.unshift("h");
- console.log(num); //['h', 'guohan', 'gh', 'gg', 'hh', 'h']
- //删除
- //对象.pop(): 尾部删除
- num.pop();
- console.log(num); //['h', 'guohan', 'gh', 'gg', 'hh']
- //对象.shift(): 头部删除
- num.shift();
- console.log(num); //['guohan', 'gh', 'gg', 'hh']
- //指定位置增加删除和修改
- //对象.splice(索引,删除的元素个数,增加的元素1,增加的元素2)
- //删除
- console.log(num.splice(1, 2)); //['gh', 'gg']
- console.log(num); //['guohan', 'hh']
- //增加
- num.splice(1,0,222,333);
- console.log(num,num.length); //['guohan', 222, 333, 'hh'] 4
- //修改
- num.splice(1,1,"gh");
- console.log(num); //['guohan', 'gh', 333, 'hh']
- //指定数组成员返回索引
- console.log(num.indexOf("guohan")); //0
- //判断指定成员是否在数组中
- console.log(num.includes("guohan")); //true
- //对象.slice(start,end): 反回数组切片左闭右开
- console.log(num.slice(1,-1)); //[222, 333]
- //对数组进行循环操作
- //for循环获取下标
- for(var data in num){
- console.log(data);
- }
- //for循环获取成员
- for(var data of num){
- console.log(data);
- }
- //对象.forEach((值,索引,数组本身)=>{代码})
- num.forEach((value,index,array)=>{
- console.log(value,index,array);
- })
- //反转数组顺序
- num.reverse();
- console.log(num); //['hh', 333, 'gh', 'guohan']
- //对象.sort(): 根据ascii码值进行排序
- console.log(num.sort());
- //以指定字符对数组进行拼接得到字符串
- console.log(num.join("")); //333ghguohanhh
- //案例:对字符串进行反转
- function strrev(str){
- ret = str.split("").reverse().join("")
- return ret;
- }
- console.log(strrev("guohan")); //333ghguohanhh
- //Array.isArray(对象): 判断指定对象是不是数组
- console.log(Array.isArray(num)); //true
- //[333, 'gh', 'guohan', 'hh']
- //高级方法
- //对象.map(指定函数): 通过指定函数对数组每个成员进行处理
- console.log(num.map((value) => typeof (value) === 'number' ? value + 1 : value)); //[334, 'gh', 'guohan', 'hh']
- console.log(num.map(function (value) {
- if (typeof (value) === 'number') {
- return value += 1;
- }else{
- return value;
- }
- })); //[334, 'gh', 'guohan', 'hh']
- //对象.filter(筛选函数): 通过指定函数对数组成员进行筛选
- console.log(num.filter((value) => typeof (value) === 'string' ? value : null)); //['gh', 'guohan', 'hh']
- console.log(num.filter((value) => typeof (value) === 'number' ? value : null)); //333]
- console.log(num.filter(function (value) {
- if (typeof (value) === 'number') {
- return value;
- } else {
- return null;
- }
- })); //333]
- //对象.reduce(函数(参数1,参数2)): 通过指定函数对数组成员进行累计操作
- console.log(num.reduce((value1, value2) => {
- return value1 + value2;
- })); //333ghguohanhh
- /**
- * python中内置函数
- * import functools
- * content = [1,22,44,"gouhan","gh"]
- *
- * #内置函数map
- * result1 = list(map(lambda x:x+2 if isinstance(x,int) else x,content))
- * print(result1) [3, 24, 46, 'gouhan', 'gh']
- *
- * #内置函数filter
- * result2 = list(filter(lambda x: isinstance(x,int),content))
- * print(result2) [1, 22, 44]
- *
- * #内置函数reduce
- * result3 = functools.reduce(lambda x,y:x+y if isinstance(x and y,int) else str(x)+y,content)
- * print(result3) 67gouhangh
- */
- //[333, 'gh', 'guohan', 'hh']
- //对象.every(函数): 判断数组成员是否均满足条件,
- console.log(num.every((value) => {
- return typeof value === 'string';
- })); //false
- //判断数组成员是否至少有一个满足条件
- console.log(num.some((value) => {
- return typeof value === 'string';
- })); //true
复制代码 JSON- //数组解包
- var array = [1,2,3,4];
- //全接受
- var [num1,num2,num3,num4] = array;
- console.log(num1,num2,num3,num4); //1 2 3 4
- //顺序接收:部分接收
- var [number1, ,number2] = array;
- console.log(number1,number2); //1 3
- //顺序接收:接收剩余数据
- var [data1,data2,...args] = array;
- console.log(args); //[3, 4]
复制代码- //数组解包
- var array = [1,2,3,4];
- //全接受
- var [num1,num2,num3,num4] = array;
- console.log(num1,num2,num3,num4); //1 2 3 4
- //顺序接收:部分接收
- var [number1, ,number2] = array;
- console.log(number1,number2); //1 3
- //顺序接收:接收剩余数据
- var [data1,data2,...args] = array;
- 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 控制台操作对象,浏览器中进行代码打印与调试- //解包在函数中的运用
- //对象解包
- function func1({x,y}){
- console.log(x+y);
- }
- func1({x:10,y:20}); //30
- //数组解包
- function func2([x,y]){
- console.log(x,y);
- }
- func2([1,2]); //1 2
- function func3([x,...args]){
- console.log(args);
- }
- func3([1,2,3,4]); //[2, 3, 4]
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |