JavaScript之对象

94 阅读5分钟

创建对象

  1. 利用 对象字面量 创建对象
var obj = {
	xxx: 'xxx',
	xxx:  0,
	xxx: false,
	xxx: function( 可以有参数 ){		//定义的方法只能是 匿名函数
		xxx  // 可以有return返回值
	},
};

调用对象中的变量 除了可以用 对象名.属性,还能用对象名['属性名']。 调用对象中的方法则不行,只能用英文圆点 .

在对象外面赋值时用等号 ,包括方法的赋值也是 如obj.fn = function(){ xxx }

  1. 利用new Object() 创建对象,在对象外面赋值
 var obj2 = new Object();
    obj2.num = 18
    obj2.flag = true
   	obj2.fun = function(num){
     	return num
  	}

构造函数

构造函数的命名规范:首字母大写

function 构造函数名(参数1,参数2,参数3,...){
	this.属性1 = 参数1;
	this.属性2 = 参数2;
	this.属性3 = 参数3;
	...
}

var一个对象 new一下构造函数,传入参数,赋值给对象,就能创建一个对象

例:

function Star(uname,age,sex) {
            this.name = uname
            this.age = age
            this.sex = sex
            this.sing = function(song){
                return song
            }
        }
   var obj3 =new Star('张国荣',47,'男')	//调用构造函数一定要有new
   console.log(obj3.sing('Monica'));
   console.log(obj3);

在这里插入图片描述 new 关键字执行过程

1 在内存中创建一个空的对象

2 this指向这个空对象

3 执行构造函数里的代码,给这个空对象添加属性和方法

4 返回这个对象(所以不需要return)


遍历对象

forvar k in  对象名){

​		console.log(k);//k输出的是属性名 ——————约定俗成用k或者keyconsole.log(对象名[k]);	//输出属性值,此处[k] 不同于前面的调用对象中属性,不需要单引号''
}	

例:

 // 遍历对象
        var obj4 = {
            name:'xxx',
            age:22,
            sex:'男',
            fn:function(num){
                console.log(num);
            }
        }
        for(var key in obj4){
            console.log(key + ':' + obj4[key]);
        }

在这里插入图片描述


内置对象

常用的有Math、Date、Array、String等。 自定义对象(自己声明赋值的对象)和内置对象是JS基础内容,属于ECMAScript

Math不是构造函数,不需要new声明,可以直接使用

Math.max() -Infinity

Math.max(1,2,'1') NaN

Math.PI 3.141592653589793

Math.abs(数值) 取绝对值 Math.abs('-1') 结果是1 会隐式转换

Math.floor() 向下取整 小数点后的都会去掉 如1.9-->1

Math.ceil() 向上取整 小数点后无论多少都进1 如1.1--> 2

Math.round() 四舍五入 注意点:x.5 往大了取 如-1.5结果是-1(-1大于-2)

Math.random() 返回[0,1)范围内的浮点数,这个方法不跟参数

例题:提供两个数min 和 max ,想要得到两个数之间的随机整数且包含这两个整数 的办法:

解答:Math.floor(Math.random() * (max - min +1 )) + min;

Date 使用:

  var date = new Date();	
  //Date() 是构造函数,要有new声明, new Date() 如果没有参数,date是系统的当前时间
  console.log(date);

  console.log('当前时间戳', Date.now());    //H5 新增的方式,获取当前时间戳
  console.log(date.getTime());//获取当前时间戳
  console.log(date.valueOf());//获取当前时间戳
  var date2 = +new Date();	//最常用
  console.log(date2);//获取当前时间戳

运行结果:

Mon May 30 2022 14:17:10 GMT+0800 (中国标准时间)
当前时间戳 1653891430335
1653891430335
1653891430335
1653891430336

+new Date( 时间 ) 获取参数时间的时间戳

例: 获取 年月日 星期数

        // 格式化日期 年月日
        var date = new Date();
        console.log(date.getFullYear());// 返回当前日期的年
        console.log(date.getMonth() + 1);// 月份 返回的月份小1个月 记得月份+1 
        console.log(date.getDate()); // 返回的是 几号
        console.log(date.getDay());//周一返回的是 1 周六返回的是 6 但是 周日返回的是0 
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var dates = date.getDate();
        var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        var day = date.getDay();
        console.log('今天是:' + year + '年' + month + '月' + dates + '日 ' + arr[day]);

输出 今天是:xxxx年x月xx日 星期X 也可以自己定义日期格式:

function getTime() {     // 自定义的方法 获取当前年月日时分秒
    var date = new Date()
    var year = date.getFullYear();
    var month = date.getMonth() + 1;    //date.getMonth()获取的是0-11 0代表一月
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes()
    var seconds = date.getSeconds()
    month = month < 10 ? "0" + month : month
    day = day < 10 ? "0" + day : day
    hours = hours < 10 ? "0" + hours : hours
    minutes = minutes < 10 ? "0" + minutes : minutes
    seconds = seconds < 10 ? "0" + seconds : seconds
    let time = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    return time;
}

输出 xxxx-xx-xx xx:xx:xx

倒计时案例

function countDown(time) {		//输入计划的时间,获取倒计时 x 天 x 时 x 分 x 秒
    var nowTime = +new Date();// 返回的是当前时间总的毫秒数
    var inputTime = +new Date(time);// 返回的是用户输入时间总的毫秒数
    var times = (inputTime - nowTime) / 1000;// times是剩余时间总的秒数 
    var d = parseInt(times / 60 / 60 / 24);// 天                除60得分 除60得时  除24得天数
    d = d <10 ? '0' + d : d;    
    var h = parseInt(times / 60 / 60 % 24);//时                 除60得分 除60得时  除24取余得不满一天剩下的小时数
    h = h < 10 ? '0' + h : h;
    var m = parseInt(times / 60 % 60);// 分                     除60得分 除60取余得不满一小时剩下的分钟数
    m = m < 10 ? '0' + m : m;
    var s = parseInt(times % 60); // 当前的秒                   除60取余得不满一分钟剩下的秒数
    s = s < 10 ? '0' + s : s;
    return d + '天' + h + '时' + m + '分' + s + '秒'
}
console.log('当前时间',getTime());		//用到上面的自定义获取时间的方法 getTime()
console.log('距离毕业典礼',countDown('2022-6-26 14:00:00'));

在这里插入图片描述


字符串对象

indexOf('xxx') 根据指定字符得出在字符串中的下标

indexOf('xxx',count) 可以指定从下标为count处开始查找

根据下标找字符串

方法名说明使用
charAt(index)返回指定位置的字符,index 是字符串的索引号str.charAt(0)
charCodeAt(index)获取指定位置处的ASCII码,index 是字符串的索引号str.charCodeAt(0)
str[index]返回指定位置处字符H5,IE8+支持,和chatAt等效

补充说明

charAt(index)的index超出最大下标或者str.charAt(-1)返回 空值

charCodeAt(index) 的index超出最大下标或者为-1,返回NaN

str[index]的index超出最大下标或者为-1,返回undefined

拼接、截取、替换、分割字符串

方法名说明
concat(str1,str2,str3...)concat() 方法用于拼接两个或多个字符串
substr(start,length)从start索引号位置开始,截取length个字符
slice(start,end)从start索引号开始截取到end,不包括end索引号直接的字符
replace(a,b)将字符串中的a替换为b,默认只会替换第一个
split('x')将字符串根据指定字符x分割,结果是数组