外观
一些对象的常用方法
forEach方法
forEach语法用于循环调用数组的每个元素,相当于增强的for循环。它接受一个函数作为参数,这个函数需要有两个参数,第一个代表每次遍历时遍历到的数组元素,第二个代表元素的索引。
const arr = [1, 2, 3, 4];
arr.forEach((el, index) => {
console.log(`${el}的索引为${index}`)
})Object.keys()方法和Object.values()方法
Object.keys(obj)方法可以获取到obj对象的所有自定义属性值,返回一个数组。
obj = {
key1: "value1",
key2: "value2",
key3: "value3"
};
console.log(Object.keys(obj)) //[ 'key1', 'key2', 'key3' ]Object.values(obj)方法可以获取到对象的所有属性值。
obj = {
key1: "value1",
key2: "value2",
key3: "value3"
};
console.log(Object.values(obj)) //[ 'value1', 'value2', 'value3' ]Object.assign(obj)
Object.assign(obj)返回obj对象的深层拷贝,与obj对象不一致。
obj = {
key1: "value1",
key2: "value2",
key3: "value3"
};
const obj2 = {};
Object.assign(obj2, Object.assign(obj))
console.log(obj2)数组reduce方法
数组的reduce方法返回一个字面值,它接受一个函数类型的参数,作用是按照参数的方法对数组元素进行累次运算,返回运算的结果。参数函数接收两个参数,第一个参数为数组的上一个值,第二个参数为当前值。
let arr = [1, 2, 3, 4];
let result = arr.reduce(function (prev, curr) {
return prev + curr
})
console.log(result) //10reduce还接受第二个参数,代表运算的初始值。
let arr = [1, 2, 3, 4];
let result = arr.reduce(function (prev, curr) {
return prev + curr
}, 10)
console.log(result) //20若没有起始值,则上一次值为数组第一个元素的值,每一次循环,将返回值作为下一此循环的上一次值,若有起始值,则上一次值为起始值。
数组map方法
数组实例的map方法用于将数组的各个元素进行处理,返回处理后的数组。
let arr1 = [1, 2, 3, 4];
let arr2 = arr1.map(function (el) {
return el > 2 ? el + 3 : el;
})
console.log(arr2) // [1, 2, 6, 7]map函数的第一个参数为一个函数,这个函数可以有三个参数。第一个参数为当前元素,这个必须包含,第二个参数为该元素的索引,可省略,第三个参数为数组本身,其他和这个方法有同样参数的方法,参数意义和此方法的参数意义基本相同,下面不再介绍。
数组filter方法
数组实例的filter方法用于过滤数组中不符合条件的数组,返回符合条件的数组。
let arr1 = [1, 2, 3, 4];
let arr2 = arr1.filter(function (el) {
return el > 2;
})
console.log(arr2) // [3, 4]数组find方法
数组实例的find方法用于找到第一个符合条件的元素,若没有则返回undefined。
let arr1 = [1, 2, -3, 4];
let arr2 = arr1.find(function (el) {
return el < 0;
})
console.log(arr2) //-3以上三个方法可以用于查找特定对象。
let arr = [
{
name: "张三",
age: 18
},
{
name: "李四",
age: 19
},
{
name: "王五",
age: 20
}
]
el = arr.find(function (el) {
return el.name === "王五";
})
console.log(el) //第三个对象函数call方法
函数call的第一个参数为thisArg,用于指定函数执行时this的值,常用于改变函数中this的值。调用call方法后相当于直接调用函数,只是改变了函数中this的指向。它的返回值就是函数的返回值。
function func() {
console.log(`this的指向:${this}`);
console.log(`参数列表:${arguments}`);
}
func(1, true, "参数之一");
func.call({key: "val"}, 1, true, "参数之一");函数apply方法
它和call方法的唯一差别就是它的第二个参数接收一个列表,表示参数列表,其他和call方法基本相似。
function func() {
console.log(`this的指向:${this}`);
console.log(`参数列表:${arguments}`);
}
func(1, true, "参数之一");
func.apply({key: "val"}, [1, true, "参数之一"]);函数bind方法
bind方法不会调用函数,但是会改变函数的指向。它的调用方式和call相同,但返回值为改变了this指向的原函数拷贝,是一个新函数。
const btn = document.querySelector("button");
btn.addEventListener("click", function () {
this.disabled = true;
setTimeout(function () {
// 原来该函数的this指向window,我们要将它改为btn
this.disabled = false;
}.bind(this), 2000)
})