简体   繁体   English

ecmascript-6函数来反转数组中的值

[英]ecmascript-6 function to reverse values in an array

Why doesn't this two codes do the same thing ? 为什么这两个代码不做相同的事情?

Can someone explain to me where is the trick ? 有人可以告诉我诀窍在哪里吗?

 function randomize(arr){ for(var i = 0; i < arr.length; i++){ const random = Math.floor(Math.random()*arr.length); let temp = arr[i]; let newR = arr[random]; [temp, newR] = [newR, temp]; } return arr; } console.log(randomize([1,2,3,4,5])); 

 function randomize(arr){ for(var i = 0; i < arr.length; i++){ const random = Math.floor(Math.random()*arr.length); [arr[i], arr[random]] = [arr[random], arr[i]]; } return arr; } console.log(randomize([1,2,3,4,5])); 

I am most grateful for your read ! 我非常感谢您的阅读!

With the following, you are swapping temp and newR however, the original array items stay intact and are not swapped. 使用以下命令,您将交换tempnewR但是原始数组项将保持不变并且不会被交换。 Hence, the output remains the same as input. 因此,输出保持与输入相同。

 let temp = arr[i];   
 let newR = arr[random];
 [temp, newR] = [newR, temp];

With the later you are swapping the array items, hence, the array gets updated. 在以后的版本中,您将交换数组项,因此,数组将被更新。

[arr[i], arr[random]] = [arr[random], arr[i]];

Because in JavaScript you cannot pass primitive values by reference, but only by value. 因为在JavaScript中,您不能通过引用传递原始值,而只能通过值传递。 Only compound values (Object, Array) can be assigned by reference. 只能通过引用分配复合值(对象,数组)。

let arr = ["one", 2, {name: "foo"}];

if you do 如果你这样做

let item = arr[0];

then you are just copying it the value. 那么您只是复制它的值。 Changing item will not modify the value of arr[i] , because there is no reference to it. 更改item不会修改arr[i]的值,因为没有引用。

But if you would do following 但是如果你愿意

let obj = arr[2];

you would have a reference to the object at the 3rd position. 您将在第3个位置引用该对象。 you could reassign obj with something different, that would not change arr[2] . 您可以用不同的方式重新分配obj,这不会更改arr[2] But if you access the name property and change it, you are changing a property of a referenced object. 但是,如果您访问name属性并对其进行更改,那么您正在更改被引用对象的属性。

obj.name = "bar";
console.log(obj === arr[2]);
console.log(arr[2].name === "bar");

obj = "something else";
console.log(arr[2] !== obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM