js高级第二天
1.数组方法
find
找满足条件的数组中第一个元素 找到了之后 不会再继续往下遍历
没找到返回undefined
const arr = [
{ username: '悟空', height: 70 },
{ username: '八戒', height: 60 },
{ username: '龙马', height: 30 },
{ username: '龙马', height: 30 }
]
const obj = arr.find((value) => value.height === 60);
console.log(obj);//{ username: '八戒', height: 60 }
findIndex
找符合条件的第一个元素的下标 找到返回这个元素的下标 没找到返回-1
const index = arr.findIndex((value) => value.height === 660);
console.log(index);//-1
includes
判断一个数组是否包含一个指定的值
const arr = ['a', 'b', 'c', 'd'];
const result = arr.includes('e');
console.log(result);//false
indexOf
搜索数组中的元素 并返回某个数据在数组中的位置 找到了 就返回这个元素的下标 没有找到则返回 -1
const arr = ['a', 'b', 'c', 'd'];
const index = arr.indexOf('h');
console.log(index);
join
将数组元素串联成一个字符串
参数可选 不写参数或传入undefined,则使用逗号作为分隔符
const arr = ['a', 'b', 'c'].map((value) => `<li>${value}</li>`);
// const arr = ['<li>a</li>', '<li>b</li>', '<li>c</li>'];
const result = arr.join('');
console.log(result);//<li>a</li><li>b</li><li>c</li>
2.Set对象
Set本身是一个对象 存放数据 数据永远不会重复 将Set当成是一个数组处理
把Set转成真正数组:const arr=[...set] 再使用map find findIdex等方法
数组转Set对象:const set=new Set([1,2,3,4])
Set对象添加数据方法:使用add方法 一次添加一个数据
set.add(1)
set.add(2)
set.add(3)
const list = [1, 4, 5, 8];
// Set对象需要new出来使用
const set = new Set(list);
console.log(set);
set.add(2)//一次只能添加一个数据
console.log(set);
3.构造函数
构造函数定义
本质 是一个函数
作用 用来创建对象
规范 首字母大写
常见构造函数:Set Array Object String Number Boolean Date
只要它被new 它就是构造函数
被new出来的对象 叫实例
构造函数的this
构造函数 默认情况下 就是返回了 this
this 指向new出来的实例
只要给构造函数中的this添加属性或者方法 那么实例自然拥有对应的属性和方法
构造函数的原型
原型本质是一个对象
当我们在创建一个构造函数的时候 原型也被创建
如果我们在原型对象上增加一个属性或者方法 那么实例也拥有了所增加的属性或方法
使用面向对象的方式来创建对象:构造函数内部定义非函数类型的属性 原型来定义函数类型的属性
function Person() {
this.hair = 100;
}
// 原型
Person.prototype.decrease=function(){
this.hair--;
}
面向对象思维---点击按钮使图片放大
javascript
<button>放大</button>
<script>
function MyImg(src) {
// body标签上能出现一张图片
const img = document.createElement('img');
img.style.transition = '2s';
// 设置 图片地址
img.src = src;
// 在body标签上看见这一张图片
document.body.append(img);
this.abc = img;
}
// 原型上写一写函数
MyImg.prototype.scale = function (num) {
// 获取到 构造函数中 创建的 img dom元素 - 提前把img dom 添加到 this的属性中
this.abc.style.transform = `scale(${num})`;
};
const myImg = new MyImg('./images/1.png'); // body标签上能出现一张图片
const myImg2=new MyImg("./images/1.png");
const button = document.querySelector('button');
button.addEventListener('click', function () {
// myImg.scale(2);//
myImg.scale(3); // 3 倍
myImg2.scale(5);
});
</script>