ES6 - 价差运算符
介绍
价差操作商
价差算子的应用案例
结论
介绍
在本文中,我们将探讨 JavaScript ES6 或 ES2015 版本中引入的一个非常强大而又简单的特性:扩展运算符。
价差操作商
展开运算符将可迭代对象展开成各个元素。可迭代对象是指任何可以遍历的对象,例如数组、映射、集合、DOM 节点列表等等。
下面给出一个简单易懂的价差运算符示例:
//An Array of fruits
const fruits = ['Apple', 'Banana', 'Watermelon'];
//Output the value of array using the spread operator
console.log(...fruits);
//Output -> Apple Banana Watermelon
扩展运算符用对象前的三个句点表示。在上面的例子中,扩展运算符用于 'fruits' 数组,数组的值通过 console.log 语句打印在一行中。
价差算子的应用案例
复制数组
我认为这是在使用 ES6 语法进行编程时会遇到的最实用的例子之一。
从下面的代码示例中需要注意的重要一点是,在将数组“animals”的元素赋值给数组“animalsCopy”时,创建的是数组“animals”元素的浅拷贝。这意味着它们持有的引用不同,您可以使用“三重相等”运算符来验证这一点。
//animals array initialized
const animals = ['dog', 'sheep', 'goat'];
//animalsCopy array is created with a Shallow copy of animals array values
const animalsCopy = [...animals];
//Display value on the console
console.log(animalsCopy);
//Output -> Array(3) ["dog", "sheep", "goat"]
console.log(animals === animalsCopy); //Output -> false
//Important thing to note here is that animals !== animalsCopy (Only a Shallow copy is made)
复制对象
这与复制数组完全相同,只不过我们使用的是对象。
//Person object
const person =
{ name : 'Skay',
age : 38
}
//Shallow copy Person object using spread operator to create personCopy object
const personCopy = {...person};
console.log(personCopy); //Output -> { name: "Skay", age: 38 }
console.log(person === personCopy); //Output -> false (Shallow copy)
合并数组
Spread 运算符提供了一种简单有效的方法来合并数组,而无需遍历数组。
const maleActors = ['Brad Pitt', 'Chris Evans', 'Matt Damon'];
const femaleActors = ['Jennifer Aniston', 'Jennifer Lawrence', 'Emma Stone'];
const movieActors = [...maleActors, ...femaleActors];
console.log(movieActors);
//Output -> Array(6) [ "Brad Pitt", "Chris Evans", "Matt Damon", "Jennifer Aniston", "Jennifer Lawrence", "Emma Stone" ]
合并对象
合并对象与合并数组类似,区别在于对象中存在“键”或“属性”。
两个物体合并时有两种可能:
- 键是唯一的 - 键/值将被复制到新对象中。
- 键在两个对象中是相同的——合并过程中,最后一个对象的值将替换前一个对象的值。
下面的代码示例将有助于更好地理解该场景。
//Person1 Object containing the attributes name & age
const person1 =
{
name : "Skay",
age : 32
};
//Person2 Object containing the attributes name, age & occupation
const person2 =
{
name : "Skay",
age: 38,
occupation: "Web Developer"
};
//Both objects are merged using the spread operator
//If key is not common between person1 & person2, then it's copied to the newPerson object
//However, for the age attribute, the value of 'person2' will be replaced with the value of 'person1'
const newPerson = {...person1, ...person2};
console.log(newPerson) ; // Output -> {name: "Skay", age: 38, occupation: "Web Developer"}
扩展运算符 - 适用于字符串
扩展运算符也适用于字符串。一个实际应用例子是从字符串中提取字符。
//'name' variable
const name = 'Skay';
//Spread Operator extracts the characters from the String and assigns to an array
const chars = [...name];
console.log(chars); //Output -> Array (4) ["S", "k", "a", "y"]
扩展运算符 - 函数的参数
这是将数组作为参数传递给函数的另一个绝佳的实用示例。不过,当使用扩展运算符作为函数参数时,代码可读性就成了一个值得讨论的问题。
在下面的代码示例中,扩展运算符会按照变量在数组中出现的顺序将它们展开到参数中。因此,1 被传递给 a,2 被传递给 b,3 被传递给 c。
//Array of numbers
const arr = [1,2,3];
//Arrow Function to add numbers
const add = (a,b,c) => a+b+c;
//Passing the array as a spread operator to the function 'add'
//The values of the array are spread across the variables in the same order
//they appeared in the array
console.log(add(...arr)); //Output -> 6
具有解构功能的价差操作
另一个常见的用例是在解构时结合扩展运算符。
解构是 ES6 引入的另一个强大特性。你可以在这里阅读更多相关内容。
在下面的代码示例中,当使用扩展运算符时,属性“occupation”、“skills”默认分配给“others”变量。
//Person Object
const person =
{
name : 'Skay',
age: 38,
occupation: 'Web Developer',
skills: 'HTML, CSS, JavaScript'
};
//Destructuring the Person object and assigning the values to name & age
//The attributes occupation & skills are automatically assigned to 'others'
//By using the spread operator
const { name, age, ...others } = person;
console.log(`Name is ${name}`); //Output -> Name is Skay
console.log(`Age is ${age}`); //Output -> Age is 38
console.log(others);
// Output -> {occupation: "Web Developer", skills: "HTML, CSS, JavaScript"}
将节点列表转换为数组
这是另一个可以使用扩展运算符的常见例子。通常,如果我们需要对页面中的列表进行任何 DOM 操作,我们会使用 `querySelectorAll` 命令从 DOM 中选择元素。
使用“querySelectorAll”命令时,它会返回一个NodeList。NodeList类似于数组,但它没有数组的高阶方法,例如forEach、map、filter等。
但是,借助扩展运算符,我们可以在一行代码中将节点列表转换为数组。
/* Note: This is a sample code & will run with HTML code*/
//Assuming there's a number of list items with the className of 'items'
//It will return a NodeList
let nodeList = document.querySelectorAll('.items');
//Using the spread operator, the nodeList is converted to an array
//This gives us the flexibility to use high-order array methods such as map, filter, etc.
var nodeArray = [...nodeList]
结论
正如我们所见,“扩展运算符”语法是 JavaScript 的一项非常便捷的功能。本文中我们已经了解了扩展运算符的以下特性:
- 将两个数组合并为一个数组。
- 只需一行代码即可将数组作为参数传递给函数。当函数需要处理大量参数时,此功能非常有用。
- 可以与解构结合使用,提取特定值并将其余值分配给单个变量。
- 可以对数组和对象进行浅拷贝。
- 诸如从字符串中提取字符或将 NodeList 转换为数组等实际用例,都可以在一行代码中实现。
希望您喜欢这篇文章。感谢您抽出时间阅读,也请您留下对这篇文章的反馈意见。
您可能也会喜欢以下文章:
文章来源:https://dev.to/skaytech/es6-spread-operator-3ced