JavaScript 中 5 个有用的数组方法
大家好,我是Aya Bouchiha,今天我将讨论 Javascript 中有用的数组方法。
每一个
every( callbackFunction ):如果数组中的所有元素都通过特定测试,则返回true ,否则返回false
const allProductsPrices = [21, 30, 55, 16, 46];
// false because of 16 < 20
const areLargerThanTwenty = allProductsPrices.every(
(productPrice) => productPrice > 20
);
// true because allProductsPrices < 60
const areLessThanSixty = allProductsPrices.every(
(productPrice) => productPrice < 60
);
一些
some( callbackFunction ):如果数组中至少有一个元素通过给定测试,则返回true ,否则返回false。
const allProductsPrices = [10, 0, 25, 0, 40];
const isThereAFreeProduct = allProductsPrices.some(
(productPrice) => productPrice === 0
);
const isThereAPreciousProduct = allProductsPrices.some(
(productPrice) => productPrice > 100
);
console.log(isThereAFreeProduct); // true
console.log(isThereAPreciousProduct); // false
充满
fill( value, startIndex = 0, endIndex = Array.length ):用给定值填充数组中的特定元素。
const numbers = [20, 254, 30, 7, 12];
console.log(numbers.fill(0, 2, numbers.length)); // [ 20, 254, 0, 0, 0 ]
// real example
const emailAddress = "developer.aya.b@gmail.com";
const hiddenEmailAddress = emailAddress.split("").fill("*", 2, 15).join("");
console.log(hiddenEmailAddress); // de*************@gmail.com
撤销
reverse():此方法反转数组中元素的顺序。
const descendingOrder = [5, 4, 3, 2, 1];
// ascendingOrder
console.log(descendingOrder.reverse()); // [ 1, 2, 3, 4, 5 ]
包括
includes( value, startIndex = 0 ):是一种数组方法,如果给定数组中存在特定值,则返回 true,否则返回 false(未找到指定元素)。
const webApps = ["coursera", "dev", "treehouse"];
console.log(webApps.includes("dev")); // true
console.log(webApps.includes("medium")); // false
概括
- every( callbackFunction ):如果数组中的所有元素都通过了给定的测试,则返回 true。
- some( callbackFunction ):如果至少有一个元素通过了给定的测试,则返回 true。
- fill( value, startIdx = 0, endIdx = arr.length ):用给定值填充指定的数组元素。
- reverse():反转数组中元素的顺序。
- includes( value, startIdx = 0 ):检查给定值是否存在于特定数组中
参考
祝你今天过得愉快!
鏂囩珷鏉ユ簮锛�https://dev.to/ayabouchiha/5-useful-array-methods-in-javascript-43c8