javascript子节点_JavaScript中的传播算子

news/2024/7/10 2:10:03 标签: javascript, js, vue, jquery, python

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子节点


http://www.niftyadmin.cn/n/1254110.html

相关文章

matlab实战演练,MATLAB基础课程 实战演练(1)

看看网上有哪些例程&#xff01;看后就会感到和算法工匠提供的课程的差距了哦&#xff01;(纯属自夸&#xff01;)用起泡法对10个数由小到大排序。即将相邻两个数比较&#xff0c;将小的调到前头。function f func_sort(x)i 1;while i<10j i1;while j <10if x(i)>x…

java整型数组转置输出,Java实现数组转置

public class DayE2 {public static void main(String[] args) {int [] datasnew int[]{1,2,3,4,5,6};int lengthdatas.length;System.out.println("源数组");//转置前for (int i 0; i < datas.length; i) {System.out.print(datas[i]);}System.out.println(&quo…

硬件保护和软件保护_什么是硬件保护?

硬件保护和软件保护A computer contains various hardware like processor, RAM, monitor etc. So OS must ensure that these devices remain intact ( not directly accessible by the user). 计算机包含各种硬件&#xff0c;例如处理器&#xff0c;RAM&#xff0c;监视器等。…

php写的html组件库,Laravel 组件之 Forms HTML 组件 (laravelcollective/html)

安装首先通过 composer 来安装这个 包, 编辑项目的 composer.json 文件. 在 require 部分 加入 laravelcollective/html :"require": {"laravelcollective/html": "5.1.*"}接下来从命令行更新 composer :composer update -vvv接下来添加 provide…

ruby 嵌套函数_Ruby嵌套有示例的while循环

ruby 嵌套函数嵌套while循环 (Nested while loop) When one while loop is living inside another while loop, it is known as nesting of while loop. It means that there are two while loops, the first one is acting as an outer loop and later one is behaving as the…

python开发人工智能的项目,Python开发项目介绍指南

Python面向对象跟Java的面向对象大同小异&#xff0c;这篇我们简单介绍一下Python面向对象。以下是小编为你整理的python开发项目入门教程类(class)是通俗的说就是事物的属性和行为的抽象。下面我们定义个动物类&#xff0c;名称和体重是动物属性&#xff0c;动物的叫是动物行为…

vector get方法_Java Vector get()方法与示例

vector get方法向量类的get()方法 (Vector Class get() method) get() method is available in java.util package. get()方法在java.util包中可用。 get() method is used to return the object that exists at the given indices in this Vector. get()方法用于返回此Vector中…

3在java中是什么类型,java的数据类型是什么

Java的主要工作是通过编程语言来制作互联网页面、制作动态效果以及网站等技术&#xff0c;以下是小编为大家搜索整理的java的数据类型是什么&#xff0c; 希望能给大家带来帮助!更多精彩内容请及时关注我们应届毕业生考试网!1&#xff1a;什么叫数据类型数据类型简单的说就是对…