JavaScript中有用的数组和对象方法

这篇文章的作者(我们今天将发表其译文)说, Syntax FM播客的其中一个问题概述了JavaScript中对象和数组的有用方法,这促使了她的想法。 这些方法可帮助开发人员编写清晰易读的代码。 它们的使用减少了对Lodash等第三方库的需求

图片

Array.prototype.filter()


Array.prototype.filter()方法创建一个新数组,只有原始数组中与指定条件匹配的那些元素才属于该数组。

▍例子


在包含有关学生信息的数组的基础上,我们将创建一个新数组,其中仅包含有关那些年龄允许他们购买酒的学生的记录。

const studentsAge = [17, 16, 18, 19, 21, 17]; const ableToDrink = studentsAge.filter( age => age > 18 ); //  ableToDrink    : [19, 21] 

Array.prototype.map()


Array.prototype.map()方法允许您基于某种方式处理另一个数组的值来创建一个新数组。 该方法非常适合修改数据;由于它不会对原始数组进行更改,因此经常在React中使用。

▍例子


基于number数组,创建一个新数组,在每个元素的开头放置$符号。

 const numbers = [2, 3, 4, 5]; const dollars = numbers.map( number => '$' + number); //      dollars: ['$2', '$3', '$4', '$5'] 

Array.prototype.reduce()


Array.prototype.reduce()方法经常被人们忽视。 它使您可以将数组缩小为一个在接收器元素中累积的值。 此方法返回的值可以是任何类型。 例如,它可以是对象,数组,字符串或数字。

▍例子


我们将使用.reduce()方法来获取数字数组元素的总和。

 const numbers = [5, 10, 15]; const total = numbers.reduce( (accumulator, currentValue) => accumulator + currentValue); //   total    30 

实际上,可以以许多有趣的方式使用此方法。 相关示例可以在MDN文档中找到。 特别是,我们谈论的是扩展数组的数组,按属性对对象进行分组,以及删除数组中的重复元素。

Array.prototype.forEach()


Array.prototype.forEach()方法将传递给它的函数应用于数组的每个元素。

▍例子


这是使用.forEach()方法将数组的每个元素输出到控制台的方法。

 const emotions = ['happy', 'sad', 'angry']; emotions.forEach( emotion => console.log(emotion) ); //   : // 'happy' // 'sad' // 'angry' 

Array.prototype.some()


Array.prototype.some()方法检查数组的至少一个元素是否与传递给它的函数指定的条件匹配。 例如,此方法在解决验证用户特权的任务中能够很好地展示自己。 可以将其视为先前考虑的.forEach()的类似物,不同之处在于,在传递给它的函数的帮助下使用时,可以对数组元素执行某些操作,直到该函数返回真实值为止,然后中断处理。

▍例子


检查数组是否至少包含一个admin字符串。

 const userPrivileges = ['user', 'user', 'user', 'admin']; const containsAdmin = userPrivileges.some( element => element === 'admin'); //  containsAdmin   true 

Array.prototype.every()


Array.prototype.every()方法类似于上述.some()方法,但是仅当数组的所有元素都满足传递给此方法的函数所指定的条件时,它才返回true

▍例子


检查数组中存储的所有估计值是否等于或大于3。

 const ratings = [3, 5, 4, 3, 5]; const goodOverallRating = ratings.every( rating => rating >= 3 ); //goodOverallRating   true 

Array.prototype.includes()


Array.prototype.includes()方法可让您知道数组是否包含给定值。 它与.some()方法类似,但是它不检查数组的元素是否符合特定条件,而是检查在调用数组时指定的值是否存在。

▍例子


检查数组中是否存在字符串元素waldo

 const names = ['sophie', 'george', 'waldo', 'stephen', 'henry']; const includesWaldo = names.includes('waldo'); // includesWaldo   true 

Array.from()


静态方法Array.from()允许您基于其他数组或字符串创建数组。 如有必要,可以向此方法传递一个函数以执行映射,该函数使您能够影响将要落入新数组中的数据。 实际上,提供了一种特殊的映射方法-Array.prototype.map() ,因此尚不清楚为什么有人可能需要Array.from()方法的此功能。

▍例子


根据字符串创建一个数组。

 const newArray = Array.from('hello'); // newArray    ['h', 'e', 'l', 'l', 'o'] 

创建一个数组,其中包含原始数值数组元素的值的两倍。

 const doubledValues = Array.from([2, 4, 6], number => number * 2); //   doubleValues    : [4, 8, 12] 

Object.values()


Object.values()方法返回传递给它的对象的属性值的数组。

▍例子


我们形成对象属性值的数组。

 const icecreamColors = {   chocolate: 'brown',   vanilla: 'white',   strawberry: 'red', } const colors = Object.values(icecreamColors); //  colors    ["brown", "white", "red"] 

Object.keys()


Object.keys()方法返回一个由对象属性名称(键)组成的数组。

▍例子


我们将形成对象属性名称的数组。

 const icecreamColors = { chocolate: 'brown', vanilla: 'white', strawberry: 'red', } const types = Object.keys(icecreamColors); //     types: ["chocolate", "vanilla", "strawberry"] 

Object.entries()


在处理传递给它的对象之后, Object.entries()方法返回一个数组,该数组包含成对的[, ]形式的数组,这些数组是属性名称和这些属性的值。

▍例子


对于我们感兴趣的对象,我们形成一个数组,其中包含有关属性名称及其值的数据。

 const weather = { rain: 0, temperature: 24, humidity: 33, } const entries = Object.entries(weather); //   entries    // [['rain', 0], ['temperature', 24], ['humidity', 33]] 

扩展运算符和数组


应用于数组的扩展运算符( spread operator ,...)允许您通过从数组中提取其元素来扩展它们。 例如,当您需要组合多个数组时,此运算符很有用。 另外,如果需要从数组中删除某些元素,则使用它不需要使用.splice()方法,因为它可以与.slice()方法结合使用,从而避免了更改原始数组。

▍例子


合并两个数组。

 const spreadableOne = [1, 2, 3, 4]; const spreadableTwo = [5, 6, 7, 8]; const combined = [...spreadableOne, ...spreadableTwo]; //  combined   : [1, 2, 3, 4, 5, 6, 7, 8] 

我们形成一个新数组,这是从中删除元素的原始数组。 在这种情况下,原始数组不应更改。

 const animals = ['squirrel', 'bear', 'deer', 'salmon', 'rat']; const mammals = [...animals.slice(0,3), ...animals.slice(4)]; // mammals   : ['squirrel', 'bear', 'deer', 'rat'] 

扩展运算符和对象


通过将扩展运算符应用于对象,可以在不更改原始对象的情况下向其添加新的属性和值(即,由于这些操作而创建了新对象)。 另外,此运算符可用于组合对象。 在此值得注意的是,应用于对象的扩展运算符不会影响嵌套在其中的对象。

▍例子


通过在原始对象上添加新属性而不更改原始对象来创建新对象。

 const spreadableObject = { name: 'Robert', phone: 'iPhone' }; const newObject = { ...spreadableObject, carModel: 'Volkswagen' } //  newObject   : // { carModel: 'Volkswagen', name: 'Robert', phone: 'iPhone' } 

其余函数参数的语法


使用函数时,可以使用其余参数语法来组织数组形式的任意数量参数的接收。

▍例子


我们打印一个包含传递给函数的参数的数组。

 function displayArgumentsArray(...theArguments) { console.log(theArguments); } displayArgumentsArray('hi', 'there', 'bud'); //      ['hi', 'there', 'bud'] 

Object.freeze()


Object.freeze()方法“冻结”一个对象,防止该对象的现有属性更改或向该对象添加新的属性和值。 有一个误解,认为此方法类似于使用const关键字声明对象,但是可以修改常量对象。

▍例子


我们“冻结”一个对象,然后尝试更改其属性并确保无法完成此操作。

 const frozenObject = { name: 'Robert' } Object.freeze(frozenObject); frozenObject.name = 'Henry'; //  frozenObject  ,     { name: 'Robert' } 

Object.seal()


Object.seal()方法允许您“密封”对象,从而防止添加新属性。 同时,可以更改现有属性。

▍例子


我们“密封”该对象,这将不允许我们向其添加新属性,但可以更改现有属性。

 const sealedObject = { name: 'Robert' } Object.seal(sealedObject); sealedObject.name = 'Bob'; sealedObject.wearsWatch = true; //  sealedObject   : { name: 'Bob' } 

Object.assign()


Object.assign()方法允许您通过将属性从一个对象复制到另一个对象来组合对象。 实际上,使用上述扩展运算符可以实现相同的效果,因此可以完全省去该方法。 应当注意,此方法与扩展运算符一样,不执行对象的深层克隆。 如果您需要现成的工具来进行对象的深层克隆,请查看Lodash库中的工具。

▍例子


让我们从两个对象中创建一个。

 const firstObject = { firstName: 'Robert' } const secondObject = { lastName: 'Cooper' } const combinedObject = Object.assign(firstObject, secondObject); //      combinedObjec : { firstName: 'Robert', lastName: 'Cooper' } 

总结


在本文中,我们讨论了JavaScript中数组和对象的有用方法。 这里讨论的许多方法都返回新的数组或对象。 这使得将它们组合成链成为可能。 这些方法不会修改源数据,这在React开发中尤其重要。 另外,在大多数情况下,使用这些方法使您可以放弃forwhilefor循环。

亲爱的读者们! 您最常使用JavaScript中的哪些数组和对象方法?

Source: https://habr.com/ru/post/zh-CN413169/


All Articles