1、this指向
(1)普通函数
this出现在函数体中,执行时表示调用该函数的对象,即谁调用的this就指向谁。
(2)箭头函数
箭头函数体中的 this 对象,是定义函数时的对象,而不是使用函数时的对象。即箭头函数的this就是离它最近的外层普通函数的this,如果外层没有普通函数,this就是window。使用call、apply、bind不能改变箭头函数this指向。
2、改变this指向
(1)call、apply、bind
① call:
window.m1.call(obj); //不带参数
window.m2.call(obj1,10,20); //带参数
② apply:
window.m1.apply(obj); //不带参数
window.m2.apply(obj1,[10,20]); //带参数
③ bind:
window.m1.bind(obj)(); //不带参数
window.m2.bind(obj1)(10,20); //带参数
(2)使用箭头函数
(3)在函数内部使用let that = this
3、数组去重
(1)新建一个数组,遍历传入的数组,值不在新数组中就加入到该新数组
function fn(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) == -1) {
newArr.push(arr[i]);
}
}
return newArr;
}
let arr = [1, 3, 3, 5, 5, 5, 6];
let re = fn(arr);
console.log(re); //[1,3,5,6]
(2)ES6的Set数据结构
let arr = [1,3,3,5,5,5,6];
//把数组变成集合,去重
let set = new Set(arr);
//把集合变成数组
arr = [...set];
console.log(arr); //[1,3,5,6]
(3)使用filter过滤函数去重
let arr = [1, 3, 3, 5, 5, 5, 6];
let re = arr.filter((item, index) => arr.indexOf(item) == index)
console.log(re); //[1,3,5,6]
(4)双重for循环
function fn(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
i++
}
}
newArr.push(arr[i])
}
return newArr;
}
let arr = [1, 3, 3, 5, 5, 5, 6];
let re = fn(arr);
console.log(re); //[1,3,5,6]
4、map、find、filter、splice使用
var result = [{
name: 'zhangsan',
age: 18
}, {
name: 'lisi',
age: 20
}, {
name: 'wangwu',
age: 22
}, {
name: 'test',
age: 24
}];
// 1、对以上数据age属性+10后获得一个新的对象后打印在控制台,建议使用map
// map():主要用于循环遍历数组,也可以根据某些条件筛选数据,不会改变原数组
let a = result.map(x => {
x.age += 10;
return x;
})
console.log(a);
// 2、对以数据查找name=wangwu的项赋值给新变量后打印在控制台,建议使用find
// 主要用于查找数组的数据,只要查找到一条符合条件的数据,直接返回,不会再继续查找下去
// 没有找到符合条件的数据返回undefined
let b = result.find(x => x.name == "wangwu");
console.log(b);
// 3、以上数据过滤掉name=lisi的项后获得新的对象,并打印在控制台,建议使用filter
// filter(): 主要用于筛选过滤数组,返回符合筛选条件的数据,不会改变原数组
let c = result.filter(x => x.name != "lisi");
console.log(c);
// 4、以上数据在索引2处增加{name:'xx'}后打印在控制台
result.splice(2, 0, {
name: 'xx',
});
console.log(result);