携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情
下面是我经常犯的错误和搞混的概念
给对象增加属性的两种方法
有两种方法,如果属性名是变量,则使用中括号的方法
- obj.name='萨达'
- obj['name']='奥德赛'
- 如果对变量名使用的对象.属性名的方法,则会把变量名作为属性名
- 像for in函数变量对象中使用的k就是变量,所以遍历属性要是用obj[k]的写法,而不是obj.k的写法,因为这样会把k当做属性名,但是obj对象中没有属性名为k的键值对
var obj = {a:1, b:2, c:3};
for (var k in obj) {
console.log("obj." + prop + " = " + obj[k]);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
indexOf和findIndex的区别
- indexOf是数组和字符串都有的方法
- indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
indexOf()方法返回调用它的String对象中第一次出现的指定值的索引,从fromIndex处进行搜索。如果未找到该值,则返回 -1。- 数组使用示例如下:
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
-字符串indexOf方法示例如下:
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// expected output: "The index of the first "dog" from the beginning is 40"
console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// expected output: "The index of the 2nd "dog" is 52"
- findIndex()是数组的方法
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。- 示例如下
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
构造函数的原型对象添加方法,不能使用箭头函数
- 注意:给构造函数的原型对象添加方法,这里不能使用箭头函数,因为我们要在函数中使用this,但是箭头函数,没有this,如果使用this,则会向上找寻this,this成为window
Array.prototype.sum = function () {
// this指向实例化对象,就是arr数组,不需要传参
return this.reduce((pre, item) => pre + item, 0)
}
console.log(arr.sum());
- 但是有一些特殊情况我们要使用箭头函数,为的是this指向上一级的this,像是下面这种情况
- 注意:在下面代码段中的document.querySelector('.header i')的注册事件中使用的是箭头函数,
- 原因是点击事件想要实例化对象关闭,,但是如果使用普通函数 this指向的是i便签dom对象
- 使用箭头函数则会到上一级查找到上一级,this为实例化对象new Modal()
- 此时就可以使用this.close()直接调用函数移除this.modalBox
- | --------------------------------------------------------------------- |
| | // 给构造函数的原型对象添加方法 |
| | Modal.prototype.open = function () { |
| | if (!document.querySelector('.modal')) { |
| | // 找到父元素,追加子元素 是盒子显示到html中 |
| | document.body.appendChild(this.modalBox) |
| | // 获取i元素 |
| | document.querySelector('.header i').addEventListener('click', () => { |
| | this.close() |
| | }) |
| | } |
| | } |
| | Modal.prototype.close = function () { |
| | // 找到父元素,移除子元素 |
| | document.body.removeChild(this.modalBox) |
| | }