Bootstrap

总结篇:10个常用的 JavaScript 函数

1. filter

此函数根据您提供的条件过滤数组,并返回一个包含满足这些条件的项目的新数组。

const temperatures = [10, 2, 30.5, 23, 41, 11.5, 3];
const coldDays = temperatures.filter(dayTemperature => {
    return dayTemperature < 20;
});
console.log("Total cold days in week were: " + coldDays.length); // 4

2. map

函数非常简单,它遍历一个数组并将每个项目转换为其他内容。

const readings = [10, 15, 22.5, 11, 21, 6.5, 93];
const correctedReadings = readings.map(reading => reading + 1.5);
console.log(correctedReadings); // gives [11.5, 16.5, 24, 12.5, 22.5, 8, 94.5]

3. some

与 非常相似,但返回布尔值。

const animals = [
    {
        name: 'Dog',
        age: 2
    },
    
    {
        name: 'Cat',
        age: 8
    },
     {
        name: 'Sloth',
        age: 6
    },
];
if(animals.some(animal => {
    return animal.age > 4
})) {
    console.log("Found some animals!")
}

4. every()

也非常类似于,但只有当数组中的每个元素都满足我们的条件时才为真。

const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));   // true

5. shift()

该方法从数组中移除第一个元素并返回移除的元素。此方法更改数组的长度。

const items = ['meat', 'carrot', 'ham', 'bread', 'fish'];
items.shift()
console.log(items); // ['carrot', 'ham', 'bread', 'fish']

6. unshift()

就像方法从数组中删除第一个元素添加它一样。此方法更改数组的长度并返回数组的新长度作为结果。

const items = ['milk', 'fish'];
items.unshift('cookie')
console.log(items); // ['cookie', 'milk', 'fish']

7. slice()

该方法将数组的一部分的浅拷贝返回到从开始到结束(不包括结束)选择的新数组对象中,其中开始和结束表示该数组中项目的索引。不会修改原始数组。

let message = "The quick brown fox jumps over the lazy dog";
let startIndex = message.indexOf('brown');
let endIndex = message.indexOf('jumps');
let newMessage = message.slice(startIndex, endIndex);
console.log(newMessage); // "brown fox "

8. splice()

下面从数组的索引 2(第三个位置,计数从 0 开始!)开始,并删除一项。

在我们的数组中,这意味着“rabbit”被移除了。splice()将返回一个新数组作为结果。

const animals = ['dog', 'cat', 'rabbit', 'shark', 'sloth'];
animals.splice(2, 1);
console.log(animals); // ["dog", "cat", "shark", "sloth"]

9. includes()

将检查数组中的每一项,并检查其中是否有任何一项包含我们的条件。它将返回一个布尔值。

const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));  //  true
console.log(pets.includes('at'));  //  false

10. reverse()

方法反转数组。要小心,因为它是破坏性的,这意味着它会改变原始数组。

const array1 = ['one', 'two', 'three', 'four'];
console.log(array1);  //  ["one", "two", "three", "four"]
const reversed = array1.reverse();
console.log(reversed);  //  ["four", "three", "two", "one"]