JavaScript 怎么对数组进行 回调操作 的不影响原数组?

WBOY
Release: 2016-06-06 20:12:52
Original
946 people have browsed it

举个例子,下面是我做好的:

我为了不影响原数组 arr2 我新创建了一个 arr3 ;
可是最后还是被影响了,

<code>var arr3=new arr2;
var arr3=new arr2();</code>
Copy after login
Copy after login

这个语法又行不通,怎么弄呢?

<code>var arr2 =new Array(10,12,16,18,13,14,15,8,7,6,1,5,2 );


var arr3=arr2;

//重排序;
arr3.sort(function(a,b){if(a==b){return 0;}else if(a>b){return -1;}else{return 1;}});

console.log(  arr2.toString() );
console.log(  arr3.toString() );</code>
Copy after login
Copy after login

回复内容:

举个例子,下面是我做好的:

我为了不影响原数组 arr2 我新创建了一个 arr3 ;
可是最后还是被影响了,

<code>var arr3=new arr2;
var arr3=new arr2();</code>
Copy after login
Copy after login

这个语法又行不通,怎么弄呢?

<code>var arr2 =new Array(10,12,16,18,13,14,15,8,7,6,1,5,2 );


var arr3=arr2;

//重排序;
arr3.sort(function(a,b){if(a==b){return 0;}else if(a>b){return -1;}else{return 1;}});

console.log(  arr2.toString() );
console.log(  arr3.toString() );</code>
Copy after login
Copy after login

你是想克隆出来一个新的数组?那这样:

<code class="javascript">var arr1 = [1, 2, 3];

var arr2 = arr1.slice();
arr2.pop();

console.log(arr1);//[1, 2, 3]
console.log(arr2);//[1, 2]</code>
Copy after login

深拷贝:

<code>var arr3=arr2.slice();</code>
Copy after login

第一段代码没明白什么意思
第二段代码中var arr3=arr2;和你所想的不一样,你需要补充一下js的基本知识,变量赋值分为传值和传址,数据是一个Object,所有的Object赋值都是传址,所以这里arr3就是arr2也就是[1,2,3],你需要将arr2进行一个copy,如@hsfzxjy那样

<code class="javascript">var arr2 =new Array(10,12,16,18,13,14,15,8,7,6,1,5,2 );

// 对需要排序的数字临时存储
var arr3= arr2.map(function(el, i) {
  return el;
})
//重排序;
arr3.sort(function(a,b){if(a==b){return 0;}else if(a>b){return -1;}else{return 1;}});

console.log(arr2.toString());//10,12,16,18,13,14,15,8,7,6,1,5,2
console.log(arr3.toString());//18,16,15,14,13,12,10,8,7,6,5,2,1</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!