class类
基本语法
class Rectangle {
constructor(length, width) {
// this 指向新的对象实例
this.length = length;
this.width = width;
}
area() {
// this 指向调用这个方法的实例
return this.length * this.width;
}
}
- this 指向新的对象实例
- this 指向调用这个方法的实例
类的实例
// 另一种生成对象的方法
const rect = new Rectangle(20, 10);
console.log(rect.area());//200
// 🍒类似对象字面值,可以动态改动属性
rect.length = 200;
console.log(rect.area(), rect);//2000 Rectangle {length: 200, width: 10, constructor: Object}
// 🍓类构建的对象与普通的对象不同,方法 area 虽然可以访问,但不属于对象本身
console.log(Object.keys(rect));//["length", "width"]
for (const x in rect) {
console.log(x, rect[x]);//length 200 width 10
}
// 🍉如果属性在类上,in 也会返回 true。
console.log('area' in rect);//true
// 🍕普通Object的方法属于对象本身
const rect2 = {
length: rect.length,
width: 30,
area() {
return this.length * this.width;
}
};
console.log(rect2.area(), Object.keys(rect2), rect2);
//["length", "width", "area"] {length: 200, width: 30, area: ƒ area()}
- 类生成对象,类的方法是所有对象实例公享的。涉及原型链知识。
- JS,类都是对象。
内置对象
内置对象就是指JS语言自带的一些对象,这些对象公开发者使用,并提供了一些常用的或是最基本而必要的功能(属性和方法)。 JS中对象分为3类:
- 自定义对象:属于ECMAScript
- 内置对象:属于ECMAScript,
Math
、Date
、Array
、String
。 - 浏览器对象:JS独有的,JS API学习
Math对象
Math对象
Math不是构造函数,不需要new来调用,直接使用里面的属性和方法。 MDN Math文档
例:封装math对象
var myMath = {
PI:2.141592653,
max:function(){
var max=arguments[0];
for (var i=1;i<=arguments.length;i++){
if(arguments[i]>max){
max=arguments[i];
}
}
return max;
}
}
Math常用内置属性和方法
属性/方法 | 描述 |
---|---|
Math.PI | 圆周率 |
Math.floor() | 向下取整 |
Math.ceil() | 向上取整 |
Math.round() | 四舍五入,其他数字都是四舍五入,只有5是往大了取 -1.1→-1 -1.5→-1 |
Math.abs() | 绝对值 |
Math.max()/Math.min() | 求最大和最小值 |
Math.random() | 返回一个随机小数[0,1) |
得到一个两数之间的随机整数
这个例子返回了一个在指定值之间的随机整数。这个值不小于 min
(如果 min
不是整数,则不小于 min
的向上取整数),且小于(不等于)max
。
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
}
得到一个两数之间的随机整数,包括两个数在内
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
日期对象
Date()对象是一个构造函数,必须使用new来调用创建我们的日期对象,即为需要实例化后才能使用。
- 如果没有输入任何参数,则Date的构造器会依据系统设置的当前时间来创建一个Date对象。
var arr = new Array();
var obj = new Object();
var date = new Date();
var date1 = new Date(2019,10,1);
console.log(date1);//返回的是11月不是10月
var date2 = new Date('2019-10-1 8:8:8');
console.log(date2);//返回的是正确的
// Tue Oct 2019 08:08:08 GMT+0800
日期格式化
方法名 | 说明 |
---|---|
getFullyear() | 获取当年 |
getMonth() | 获取当月 0~11 要+1 |
getDate() | 获取当前日期 |
getDay() | 获取星期几 周日0~周六6 |
getHours() | 获取当前小时 |
getMinutes() | 获取当前分钟 |
getSeconds | 获取当前秒钟 |
//封装一个函数返回当前的时分秒
function getTime() {
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h;
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
return h + ':' + m + ':' + s;
}
console.log(getTime())
四种方法获取Dtae总的毫秒数(时间戳)
- Date对象是基于1970年1月1日起的毫秒数。
//1.valueOf getTime
var time = new Date();
console.log(date.valueOf());
console.log(date.getTime());
//2. 简单写法(最常用)
var date1 = +new Date();
console.log(date1);
//3. H5新增的 获得总的毫秒数
console.log(Date.now());
案例:倒计时
function countDown(time) {
var nowTime = +new Date();//当前时间总的毫秒数
var inputTime +new Date(time);//用户输入时间总的毫秒数
var times = (inputTime - nowTime)/1000; // 1000
var d = parseInt(times / 60 / 60 / 24);
var h = parseInt(times / 60 / 60 % 24);
var m = parseInt(times / 60 % 60);
var s = parseInt(times % 60);
return d + '天' + h + '时' + m + '分' + s + '秒';
}
案例:用 Date 来在网页中动态显示时间
function getCurrentTimeStr() {
const date = new Date();
const hour = date.getHours();
const minues = date.getMinutes();
const second = date.getSeconds();
// 让冒号闪烁
const separator = second % 2 ? " " : ":";
return [hour, minues, second].join(separator);
}
setInterval(() => {
const str = getCurrentTimeStr();
document.body.innerHTML =
'<span style="font-size: 30px;font-family: monospace;">' + str + "</span>";
}, 1000);
数组对象
字符串对象
字符串不可变
字符串里面的值不可变,虽然看上去可以改变内容,但其实是地址变了,内存中新开辟了一个内存空间。
var str = 'abc';
str = 'hello';
//当重新给 str 赋值的时候,常量'abc'不会被修改,依然在内存中。
//由于字符串不可变,在大量拼接字符串的时候会有效率问题:
var str = '';
for(var i = 0; i < 100000 ;i++){
str += i;
}
console.log(str);//这个结果需要花费大量时间来显示,因为需要不断开辟新的空间
//所以不要大量地对字符串重新赋值或者拼接字符串
常用方法
字符串所有方法,都不会修改字符串本身,操作完成会返回一个新的字符串。
方法名 | 说明 |
---|---|
indexOf('要查找的字符',[开始的位置]) | 返回指定内容在元字符串中的位置,如果找不到就返回-1 |
lastIndexOf() | 从后往前找,只找第一个匹配的 |
求某个字符出现的位置和次数
var str = "ofsjhfofsddfofsodfdofdsfoofd";
var idnex = str.indexOf('o');
var num = 0;
while (index !== -1) {
console.log(index);
num ++;
index = str.indexOf('o',index+1);
}
根据位置返回字符(重点)
方法名 | 说明 |
---|---|
charAt(index) | 返回指定位置的字符 |
charCodeAt(index) | 获取指定位置处的ASCll码 |
str[index] | 获取指定位置处的字符 HTML5, IE8+支持 和charAt()等效 |
//1.charAt(index)
var str = 'andy';
console.log(str.charAt(3));
for (var i = 0; i < str.length; i++) {
console.log(str.charAt(i));
}
//2.charCodeAt(index)
console.log(str.charCodeAt(0));//97 目的:判断用户按下了哪个键
//3. str[index]
console.log(str[0]);//a
判断一个字符串中出现最多的字符,并统计其次数。
var str = 'afkdofeooofdjfsa';
var o = {};
for (var i = 0; i < str.length; i++) {
var chars = str.charAt(i);
if (o[chars]) {
o[chars]++;
} else {
o[chars] = 1;
}
}
console.log(o);
var max = 0;
var ch = '';//全局变量存哪个字符出现次数最多
for (var k in o) {
if(o[k] > max) {
max = o[k];
ch = k;
}
}
console.log(max);//最多的出现次数
console.log(ch)
方法名 | 说明 |
---|---|
replace('被替换的字符','替换为的字符') | 只会替换第一个字符 |
split('分隔符') | 字符转换为数组 |
把一个字符串里的所有o
替换为*
var str1 = 'r4jfroffopfdoofdofsd';
while (str1.indexOf('o')!==1) {
str1 = str1.replace('o', '*');
}
把字符串转换为数组
var str = 'red, pink, blue';
console.log(str.split(','));
var str1 = 'red&pink&blue';
console.log(str2.split('&'));
基本包装类型(基本类型的包装对象)
三个简单的数据类型:String、Number、Boolean。基本包装类型就是把简单的数据类型包装成复杂数据类型,这样基本数据类型就有了属性和方法。
原理
以下代码是可以执行的:
var str = 'andy';
console.log(str.length);
虽然字符串是简单的数据类型,但是依然能使用属性length。因为js把字符串类型包装成了复杂数据类型:
//1.生成临时变量,把简单类型包装为复杂数据类型
var temp = new String('andy');
//2.赋值给我们声明的字符变量
str = temp;
//3.销毁临时变量
temp = null;
实际使用
调用方法,不需要使用new Number/String/Boolean
,使用基础类型的时候,js 会自动帮我们包装成对应的对象:
- 字符串
console.log('1234'.length);//4
- 数字
数字后面不能直接加
.
,js 解析语法时认为这是一个浮点数,所以需要加一层括号 ()。// // 2.toFixed(3) // ❌ console.log((2).toFixed(3));//2.000