如何在JavaScript中克隆数组

JavaScript has many ways to do anything. I’ve written on 10 Ways to Write pipe/compose in JavaScript, and now we’re doing arrays.

JavaScript有许多方法可以执行任何操作。 我已经写了10种用JavaScript编写管道/组合的方法 ,现在我们正在做数组。

1.传播算子(浅副本) (1. Spread Operator (Shallow copy))

Ever since ES6 dropped, this has been the most popular method. It’s a brief syntax and you’ll find it incredibly useful when using libraries like React and Redux.

自从ES6删除以来,这一直是最受欢迎的方法。 这是一个简短的语法,在使用像React和Redux这样的库时,您会发现它非常有用。

numbers = [1, 2, 3];
numbersCopy = [...numbers];

Note: This doesn’t safely copy multi-dimensional arrays. Array/object values are copied by reference instead of by value.

注意:这不能安全地复制多维数组。 数组/对象值是通过引用而不是value复制的。

This is fine

这可以

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

这样不好

nestedNumbers = [[1], [2]];
numbersCopy = [...nestedNumbers];numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

2. Good Old for()循环(浅副本) (2. Good Old for() Loop (Shallow copy))

I imagine this approach is the least popular, given how trendy functional programming’s become in our circles.

我想这种方式是流行的,时髦给出函数式编程在我们的圈子怎么成了。

Pure or impure, declarative or imperative, it gets the job done!

纯净或不纯净,陈述性或命令性,就可以完成工作!

numbers = [1, 2, 3];
numbersCopy = [];for (i = 0; i < numbers.length; i++) {numbersCopy[i] = numbers[i];
}

Note: This doesn’t safely copy multi-dimensional arrays. Since you’re using the = operator, it’ll assign objects/arrays by reference instead of by value.

注意:这不能安全地复制多维数组。 由于使用的是=运算符,它将按引用而不是按分配对象/数组。

This is fine

这可以

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

这样不好

nestedNumbers = [[1], [2]];
numbersCopy = [];for (i = 0; i < nestedNumbers.length; i++) {numbersCopy[i] = nestedNumbers[i];
}numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

3. Good Old while()循环(浅副本) (3. Good Old while() Loop (Shallow copy))

Same as for—impure, imperative, blah, blah, blah…it works! ?

for -impure,势在必行,等等,等等,等等...它的作品! ?

numbers = [1, 2, 3];
numbersCopy = [];
i = -1;while (++i < numbers.length) {numbersCopy[i] = numbers[i];
}

Note: This also assigns objects/arrays by reference instead of by value.

注意:这还会通过引用而不是value分配对象/数组。

This is fine

这可以

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

这样不好

nestedNumbers = [[1], [2]];
numbersCopy = [];i = -1;while (++i < nestedNumbers.length) {numbersCopy[i] = nestedNumbers[i];
}numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

4. Array.map(浅副本) (4. Array.map (Shallow copy))

Back in modern territory, we’ll find the map function. Rooted in mathematics, map is the concept of transforming a set into another type of set, while preserving structure.

回到现代领域,我们将找到map函数。 map 起源于数学 ,它是在保留结构的同时将集合转换为另一种类型的集合的概念。

In English, that means Array.map returns an array of the same length every single time.

用英语来说,这意味着Array.map返回相同长度的数组。

To double a list of numbers, use map with a double function.

要将数字列表加倍,请使用带有double函数的map

numbers = [1, 2, 3];
double = (x) => x * 2;numbers.map(double);

克隆呢? (What about cloning??)

True, this article’s about cloning arrays. To duplicate an array, just return the element in your map call.

没错,本文是关于克隆数组的。 要复制数组,只需在map调用中返回元素即可。

numbers = [1, 2, 3];
numbersCopy = numbers.map((x) => x);

If you’d like to be a bit more mathematical, (x) => x is called identity. It returns whatever parameter it’s been given.

如果您想更加数学化, (x) => x称为identity 。 它返回给定的任何参数。

map(identity) clones a list.

map(identity)克隆一个列表。

identity = (x) => x;
numbers.map(identity);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

注意:这还会通过引用而不是通过value分配对象/数组。

5. Array.filter(浅拷贝) (5. Array.filter (Shallow copy))

This function returns an array, just like map, but it’s not guaranteed to be the same length.

该函数返回一个数组,就像map一样,但是不能保证长度相同。

What if you’re filtering for even numbers?

如果您要过滤偶数数怎么办?

[1, 2, 3].filter((x) => x % 2 === 0);
// [2]

The input array length was 3, but the resulting length is 1.

输入数组的长度为3,但结果长度为1。

If your filter's predicate always returns true, however, you get a duplicate!

如果您的filter的谓词始终返回true ,那么您将得到一个重复项!

numbers = [1, 2, 3];
numbersCopy = numbers.filter(() => true);

Every element passes the test, so it gets returned.

每个元素均通过测试,因此将其返回。

Note: This also assigns objects/arrays by reference instead of by value.

注意:这还会通过引用而不是value分配对象/数组。

6. Array.reduce(浅副本) (6. Array.reduce (Shallow copy))

I almost feel bad using reduce to clone an array, because it’s so much more powerful than that. But here we go…

使用reduce克隆数组几乎让我感到难过,因为它的功能要强大得多。 但是,我们开始…

numbers = [1, 2, 3];numbersCopy = numbers.reduce((newArray, element) => {newArray.push(element);return newArray;
}, []);

reduce transforms an initial value as it loops through a list.

当它循环遍历列表时, reduce转换初始值。

Here the initial value is an empty array, and we’re filling it with each element as we go. That array must be returned from the function to be used in the next iteration.

这里的初始值是一个空数组,我们将在每个元素中填充它。 该数组必须从函数中返回,以在下一次迭代中使用。

Note: This also assigns objects/arrays by reference instead of by value.

注意:这还会通过引用而不是value分配对象/数组。

7. Array.slice(浅拷贝) (7. Array.slice (Shallow copy))

slice returns a shallow copy of an array based on the provided start/end index you provide.

slice根据您提供的开始/结束索引返回数组的浅表副本。

If we want the first 3 elements:

如果我们想要前三个元素:

[1, 2, 3, 4, 5].slice(0, 3);
// [1, 2, 3]
// Starts at index 0, stops at index 3

If we want all the elements, don’t give any parameters

如果我们需要所有元素,请不要提供任何参数

numbers = [1, 2, 3, 4, 5];
numbersCopy = numbers.slice();
// [1, 2, 3, 4, 5]

Note: This is a shallow copy, so it also assigns objects/arrays by reference instead of by value.

注意:这是一个浅表副本,因此它也按引用而不是按分配对象/数组。

8. JSON.parse和JSON.stringify(深复制) (8. JSON.parse and JSON.stringify (Deep copy))

JSON.stringify turns an object into a string.

JSON.stringify将对象转换为字符串。

JSON.parse turns a string into an object.

JSON.parse将字符串转换为对象。

Combining them can turn an object into a string, and then reverse the process to create a brand new data structure.

将它们组合在一起可以将一个对象变成一个字符串,然后逆转该过程以创建一个全新的数据结构。

Note: This one safely copies deeply nested objects/arrays!

注意:此 安全复制深层嵌套的对象/数组

nestedNumbers = [[1], [2]];
numbersCopy = JSON.parse(JSON.stringify(nestedNumbers));numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);// [[1], [2]]
// [[1, 300], [2]]
// These two arrays are completely separate!

9. Array.concat(浅副本) (9. Array.concat (Shallow copy))

concat combines arrays with values or other arrays.

concat将数组与值或其他数组组合。

[1, 2, 3].concat(4); // [1, 2, 3, 4]
[1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]

If you give nothing or an empty array, a shallow copy’s returned.

如果不提供任何内容或提供空数组,则返回浅表副本。

[1, 2, 3].concat(); // [1, 2, 3]
[1, 2, 3].concat([]); // [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

注意:这还会通过引用而不是value分配对象/数组。

10. Array.from(浅副本) (10. Array.from (Shallow copy))

This can turn any iterable object into an array. Giving an array returns a shallow copy.

这可以将任何可迭代对象转换为数组。 提供数组将返回浅表副本。

numbers = [1, 2, 3];
numbersCopy = Array.from(numbers);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

注意:这还会通过引用而不是通过value分配对象/数组。

结论 (Conclusion)

Well, this was fun ?

好吧,这很有趣吗?

I tried to clone using just 1 step. You’ll find many more ways if you employ multiple methods and techniques.

我尝试仅用1个步骤进行克隆。 如果您采用多种方法和技术,则会发现更多方法。

翻译自: https://www.freecodecamp.org/news/how-to-clone-an-array-in-javascript-1d3183468f6a/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391628.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode 227. 基本计算器 II(栈)

给你一个字符串表达式 s &#xff0c;请你实现一个基本计算器来计算并返回它的值。 整数除法仅保留整数部分。 示例 1&#xff1a; 输入&#xff1a;s “32*2” 输出&#xff1a;7 解题思路 利用两个栈&#xff0c;一个记录操作数&#xff0c;一个记录操作符&#xff0c;…

100米队伍,从队伍后到前_我们的队伍

100米队伍,从队伍后到前The last twelve months have brought us a presidential impeachment trial, the coronavirus pandemic, sweeping racial justice protests triggered by the death of George Floyd, and a critical presidential election. News coverage of these e…

idea使用 git 撤销commit

2019独角兽企业重金招聘Python工程师标准>>> 填写commit的id 就可以取消这一次的commit 转载于:https://my.oschina.net/u/3559695/blog/1596669

ES6标准入门(第二版)pdf

下载地址&#xff1a;网盘下载 内容简介 ES6&#xff08;又名 ES2105&#xff09;是 JavaScript 语言的新标准&#xff0c;2015 年 6 月正式发布后&#xff0c;得到了迅速推广&#xff0c;是目前业界超级活跃的计算机语言。《ES6标准入门&#xff08;第2版&#xff09;》…

hexo博客添加暗色模式_我如何向网站添加暗模式

hexo博客添加暗色模式同一个网站&#xff0c;两种不同的配色方案 (Same website, two different color schemes) Last year I made it a point to redesign my website from scratch. I wanted something simple and minimalist looking that clearly stated what this was — …

leetcode 331. 验证二叉树的前序序列化

序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时&#xff0c;我们可以记录下这个节点的值。如果它是一个空节点&#xff0c;我们可以使用一个标记值记录&#xff0c;例如 #。_9_/ \3 2/ \ / \4 1 # 6 / \ / \ / \ # # # # # # 例如&#xff0…

mongodb数据可视化_使用MongoDB实时可视化开放数据

mongodb数据可视化Using Python to connect to Taiwan Government PM2.5 open data API, and schedule to update data in real time to MongoDB — Part 2使用Python连接到台湾政府PM2.5开放数据API&#xff0c;并计划将数据实时更新到MongoDB —第2部分 目标 (Goal) This ti…

4.kafka的安装部署

为了安装过程对一些参数的理解&#xff0c;我先在这里提一下kafka一些重点概念,topic,broker,producer,consumer,message,partition,依赖于zookeeper, kafka是一种消息队列,他的服务端是由若干个broker组成的&#xff0c;broker会向zookeeper&#xff0c;producer生成者对应一个…

javascript初学者_针对JavaScript初学者的调试技巧和窍门

javascript初学者by Priyanka Garg由Priyanka Garg My intended audience for this tutorial is beginner programmers. You’ll learn about frustration-free debugging with chrome dev tools.本教程的目标读者是初学者。 您将学习使用chrome开发工具进行无挫折的调试。 D…

leetcode 705. 设计哈希集合

不使用任何内建的哈希表库设计一个哈希集合&#xff08;HashSet&#xff09;。 实现 MyHashSet 类&#xff1a; void add(key) 向哈希集合中插入值 key 。 bool contains(key) 返回哈希集合中是否存在这个值 key 。 void remove(key) 将给定值 key 从哈希集合中删除。如果哈希…

ecshop 前台个人中心修改侧边栏 和 侧边栏显示不全 或 导航现实不全

怎么给个人中心侧边栏加项或者减项 在模板文件default/user_menu.lbi 文件里添加或者修改,一般看到页面都会知道怎么加,怎么删,这里就不啰嗦了 添加一个栏目以后,这个地址跳的页面怎么写 这是最基本的一个包括左侧个人信息,头部导航栏 <!DOCTYPE html PUBLIC "-//W3C//…

leetcode 706. 设计哈希映射

不使用任何内建的哈希表库设计一个哈希映射&#xff08;HashMap&#xff09;。 实现 MyHashMap 类&#xff1a; MyHashMap() 用空映射初始化对象 void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 key 已经存在于映射中&#xff0c;则更新其对应…

数据库语言 数据查询_使用这种简单的查询语言开始查询数据

数据库语言 数据查询Working with data is becoming an increasingly important skill in the modern workplace. 在现代工作场所中&#xff0c;处理数据已成为越来越重要的技能。 Data is no longer the domain of analysts and software engineers. With todays technology,…

面向对象编程思想-观察者模式

一、引言 相信猿友都大大小小经历过一些面试&#xff0c;其中有道经典题目&#xff0c;场景是猫咪叫了一声&#xff0c;老鼠跑了&#xff0c;主人被惊醒&#xff08;设计有扩展性的可加分&#xff09;。对于初学者来说&#xff0c;可能一脸懵逼&#xff0c;这啥跟啥啊是&#x…

typescript 使用_如何使用TypeScript轻松修改Minecraft

typescript 使用by Josh Wulf通过乔什沃尔夫(Josh Wulf) 如何使用TypeScript轻松修改Minecraft (How to modify Minecraft the easy way with TypeScript) Usually, modifying Minecraft requires coding in Java, and a lot of scaffolding. Now you can write and share Min…

Python:在Pandas数据框中查找缺失值

How to find Missing values in a data frame using Python/Pandas如何使用Python / Pandas查找数据框中的缺失值 介绍&#xff1a; (Introduction:) When you start working on any data science project the data you are provided is never clean. One of the most common …

监督学习-回归分析

一、数学建模概述 监督学习&#xff1a;通过已有的训练样本进行训练得到一个最优模型&#xff0c;再利用这个模型将所有的输入映射为相应的输出。监督学习根据输出数据又分为回归问题&#xff08;regression&#xff09;和分类问题&#xff08;classfication&#xff09;&#…

leetcode 54. 螺旋矩阵(递归)

给你一个 m 行 n 列的矩阵 matrix &#xff0c;请按照 顺时针螺旋顺序 &#xff0c;返回矩阵中的所有元素。 示例 1&#xff1a; 输入&#xff1a;matrix [[1,2,3],[4,5,6],[7,8,9]] 输出&#xff1a;[1,2,3,6,9,8,7,4,5] 示例 2&#xff1a; 输入&#xff1a;matrix [[1,…

微服务架构技能

2019独角兽企业重金招聘Python工程师标准>>> 微服务架构技能 博客分类&#xff1a; 架构 &#xff08;StuQ 微服务技能图谱&#xff09; 2课程简介 本课程分为基础篇和高级篇两部分&#xff0c;旨在通过完整的案例&#xff0c;呈现微服务的开发、测试、构建、部署、…

phpstorm 调试_PhpStorm中的多用户调试

phpstorm 调试by Ray Naldo雷纳尔多(Ray Naldo) PhpStorm中的多用户调试 (Multi-User Debugging in PhpStorm) 使用Xdebug和DBGp代理 (Using Xdebug and DBGp Proxy) “Er, wait a minute… Don’t you just use xdebug.remote_connect_back which has been introduced since …