Home  >  Article  >  Web Front-end  >  Reasons and solutions for object deep copy failure in js (code)

Reasons and solutions for object deep copy failure in js (code)

不言
不言Original
2018-08-21 15:44:321284browse

This article brings you the reasons and solutions (code) for the failure of deep copying of objects in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

js I have experienced it before I know that it is actually a bit tricky.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>测试</title>
		<script type="text/javascript">
			// 排序算法
		   function bubbleSort(arr) {
			  var len = arr.length;
			  for (var i = 0; i < len; i++) {
			    for (var j = 0; j < len - 1 - i; j++) {
			      if (arr[j] > arr[j+1]) { //相邻元素两两对比
			        var temp = arr[j+1]; //元素交换
			        arr[j+1] = arr[j];
			        arr[j] = temp;
			      }
			    }
			  }
			  return arr;
			}
		    
		    // 定义一个json ab
			var ab = {a:[2,1,3,9,4],b:[8,5,3]}
			// 定义一个json bc
			var bc = {};
			// 将json ab 深拷贝给json bc
			for(var i in ab){
				bc[i]=ab[i];
			}
			
			// 对json bc 排序
			bubbleSort(bc[&#39;a&#39;])
			bubbleSort(bc[&#39;b&#39;])
			
			// 分别打印 json ab ,json bc ,发现经过排序之后 对 json bc排序之后,
			// json ab也被排序,此时意味着深层拷贝失败
			document.write(&#39;-----------------------&#39;+&#39;<br/>&#39;);
			document.write(JSON.stringify(ab));
			document.write(&#39;<br/>&#39;+&#39;-----------------------&#39;+&#39;<br/>&#39;);
			document.write(JSON.stringify(bc));
			
		</script>
	</head>
	<body>
		
	</body>
</html>

My result at that time was this:

The original Object is: {a:[ 2,1,3,9,4],b:[8,5,3]}

After all kinds of brain-burning, I finally discovered the reason Here:

This deep copy will invalidate the copy if the copied objects are sorted. After the copied objects are sorted Changes will still be copied to the previous initial object

#So just change the object copy (copy) method, and the example is as follows:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>测试</title>
		<script type="text/javascript">
			// 排序算法
		   function bubbleSort(arr) {
			  var len = arr.length;
			  for (var i = 0; i < len; i++) {
			    for (var j = 0; j < len - 1 - i; j++) {
			      if (arr[j] > arr[j+1]) { //相邻元素两两对比
			        var temp = arr[j+1]; //元素交换
			        arr[j+1] = arr[j];
			        arr[j] = temp;
			      }
			    }
			  }
			  return arr;
			}
		    
		    // 定义一个json ab
			var ab = {a:[2,1,3,9,4],b:[8,5,3]}
			// 定义一个json bc
			var bc = {};
			// 将json ab 深拷贝给json bc
			/*for(var i in ab){
				bc[i]=ab[i];
			}*/
			
			 function clone(obj) {
                // Handle the 3 simple types, and null or undefined or function
                if (null == obj || "object" != typeof obj) return obj;

                // Handle Date
                if (obj instanceof Date) {
                    var copy = new Date();
                    copy.setTime(obj.getTime());
                    return copy;
                }
                // Handle Array or Object
                if (obj instanceof Array | obj instanceof Object) {
                    var copy = (obj instanceof Array)?[]:{};
                    for (var attr in obj) {
                        if (obj.hasOwnProperty(attr))
                            copy[attr] = clone(obj[attr]);
                    }
                    return copy;
                }
                throw new Error("Unable to clone obj! Its type isn&#39;t supported.");
            }
			
			bc = clone(ab);
			// 对json bc 排序
			bubbleSort(bc[&#39;a&#39;])
			bubbleSort(bc[&#39;b&#39;])
			
			// 分别打印 json ab ,json bc ,发现经过排序之后 对 json bc排序之后, json ab也被排序,此时意味着深层拷贝失败
			document.write(&#39;-----------------------&#39;+&#39;<br/>&#39;);
			document.write(JSON.stringify(ab));
			document.write(&#39;<br/>&#39;+&#39;-----------------------&#39;+&#39;<br/>&#39;);
			document.write(JSON.stringify(bc));
			
		</script>
	</head>
	<body>
		
	</body>
</html>

The result was perfect this time!

Related recommendations:

Reasons and solutions for failure to load css and js files in the php ci framework,

JavaScript Detailed explanation of deep and shallow copy examples of objects

The above is the detailed content of Reasons and solutions for object deep copy failure in js (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn