javascript子节点_JavaScript中的传播算子

javascript子节点

JavaScript传播运算符 (JavaScript Spread Operator)

The spread operator came out in ES6 and has great functionality for arrays in JavaScript. With a major update in ES9, the spread operator is now extended to objects in addition to arrays. In this article, we'll talk about the spread operator, how to use it and where to use it.

传播算子是ES6中推出的,它具有JavaScript中数组的强大功能。 在ES9中进行了重大更新后, 扩展运算符现在扩展到了除数组之外的对象。 在本文中,我们将讨论传播运算符,如何使用它以及在何处使用它。

The spread operator looks something like ... and allows us to spread the items contained in an iterable. An iterable can be visualized as anything on which we can add loops to traverse them like arrays, strings, objects, etc.

传播算子看起来像...,并允许我们传播迭代器中包含的项目。 迭代器可以可视化为任何我们可以在其上添加循环以遍历它们的东西,例如数组,字符串,对象等。

let arr=[1,2,3,4];
console.log(arr); 	//(4) [1, 2, 3, 4]
console.log(...arr); 	//1 2 3 4

Notice how the first console.log() gets us the whole array whereas the second one just gives us the elements of the array? We have used the spread operator to spread the values of the array since each value of the array can be iterated over. This is a very basic use case of the spread operator.

注意第一个console.log()是如何获取整个数组的,而第二个console.log()是如何获取数组的元素的? 由于可以迭代数组的每个值,因此我们使用了散布运算符来散布数组的值。 这是扩展运算符的一个非常基本的用例。

对对象使用扩展运算符 (Using the spread operator with objects)

var people=[
    {name: 'Fuzzy', age:20},
    {name: 'Stella', age:18},
    {name: 'Banku' , age: 14}
]

console.log(people)
console.log(...people);

Output

输出量

(3) [{…}, {…}, {…}]	 
{name: "Fuzzy", age: 20} {name: "Stella", age: 18} {name: "Banku", age: 14}

We have used the spread operator to spread over the values of an array which is essentially an array of objects.

我们已经使用了散布算子来散布本质上是对象数组的数组的值。

重要用例 (Important Use Cases)

const player={
    strength: 50,
    agility: 40,
    health: 100
}

const player2=player;
player2.health=0;
console.log(player2);
console.log(player);

Output

输出量

{strength: 50, agility: 40, health: 0}
{strength: 50, agility: 40, health: 0}

We have an object which gives us some properties of a player like strength, agility, health, etc. We declare another object player2 and set its health to 0. So now player2 will have a health of 0. However, when we see the health of our original player object, it also becomes 0. How did this happen? We only changed the health of player2, player should have stayed unaffected.

我们有一个对象,该对象为我们提供了玩家的一些属性,例如力量 , 敏捷性 , 健康等。我们声明另一个对象player2并将其运行状况设置为0。因此,现在player2的运行状况将为0。但是,当我们看到运行状况时原始播放器对象的,它也变为0。这是怎么发生的? 我们只更改了player2的运行状况, 该 玩家应该保持不受影响。

The answer lies in the fact that objects are non-primitive data types. When we created player2 we referenced it to the same memory location as that of player. Hence both share the same values and changing one changes the properties of the other. You can confirm this by,

答案在于对象是非原始数据类型。 创建player2时,我们将其引用到与player相同的存储位置。 因此,两者共享相同的值,更改一个将更改另一个的属性。 您可以通过以下方式进行确认:

    player===player2;   //true

JavaScript has treated both the objects as one. How to tackle this problem?

JavaScript将两个对象都视为一个对象。 如何解决这个问题?

传播运算符以初始化对象存储器 (Spread operator to initialize the object memory )

const player={
    strength: 50,
    agility: 40,
    health: 100
}

const player2={...player};
player2.health=0;
console.log(player2);
console.log(player);

Output

输出量

{strength: 50, agility: 40, health: 0}
{strength: 50, agility: 40, health: 100}

Now both player and player2 refer to different memory locations. We have used the spread operator to destructure the player object and cloned or created a copy of the player object and assigned it to player2. Whatever changes we make for player2 are changed only in this copy and the original values remain unchanged for the player object.

现在, player和player2都引用了不同的内存位置。 我们使用了散布运算符来解构玩家对象,并克隆或创建玩家对象的副本并将其分配给player2 。 我们对player2所做的任何更改都仅在此副本中更改,并且该player对象的原始值保持不变。

Thus, this way we can easily clone arrays and objects without worrying about immutability.

因此,通过这种方式,我们可以轻松克隆数组和对象,而不必担心不变性

Another important use case of the spread operator is to convert array-like objects to arrays. We know that querying the DOM does not give us an object or an array, it gives us an array-like object like a nodelist or an HTML collection. We can easily convert this to an array using the spread operator.

散布运算符的另一个重要用例是将类似数组的对象转换为数组。 我们知道查询DOM不会给我们对象或数组,而是给我们一个像数组的对象,如节点列表或HTML集合 。 我们可以使用spread运算符轻松地将其转换为数组。

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="styles.css">
    <title>Events in DOM</title>

</head>

<body>

    <div class="player">
        <p>Fuzzy </p>
    </div>
    <div class="player">
        <p>Stella </p>
    </div>
    <div class="player">
        <p>Banku</p>
    </div>
    <div class="player">
        <p>Garry </p>
    </div>
    <div class="player">
        <p>Damon </p>
    </div>
    <div class="player">
        <p>Reiki </p>
    </div>
    <div class="player">
        <p>Leila</p>
    </div>

</body>

<script>
    const players = document.getElementsByClassName('.player');
    console.log(players);

    const playersArr = [...players];
    console.log(playersArr);
</script>

</html>

Output

输出量

HTMLCollection []
 []

The first one returns us an HTML Collection whereas the second one returns us an array. Thus we have converted an HTML collection into an array.

第一个返回给我们一个HTML集合,而第二个返回给我们一个数组 。 因此,我们将HTML集合转换为数组

    players.forEach
    //undefined
    playersArr.forEach;
    //ƒ forEach() { [native code] }

And we can also easily use the forEach method on our new array.

而且,我们还可以轻松地在新数组上使用forEach方法

Sometimes using the spread operator for passing in arguments to a method or a function comes in very handy. Let's say we have an array of numbers and we have to find the maximum out of all of them. You might say one approach to this could be looping through all elements and comparing every two consecutive elements or simply sorting the element, but if we use the inbuilt max function in the Math object it'll save us some considerable lines of code.

有时使用传播运算符将参数传递给方法或函数非常方便。 假设我们有一个数字数组,我们必须从所有数字中找出最大值。 您可能会说一种解决方法是遍历所有元素并比较每两个连续的元素,或者只是对元素进行排序,但是如果我们在Math对象中使用内置的max函数,它将为我们节省很多代码。

var arr=[8,-12,866,7,-44,0,81,11,-3123,1283];
console.log(Math.max(...arr)); 
//Output: 1283

Thus the spread operator comes in handy in a lot of scenarios especially in cloning non-primitive data types, converting array-like objects to arrays and passing arguments to methods and functions.

因此, 散布运算符在很多情况下都派上用场,特别是在克隆非原始数据类型,将类似数组的对象转换为数组并将参数传递给方法和函数时。

翻译自: https://www.includehelp.com/code-snippets/spread-operator-in-javascript.aspx

javascript子节点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值