11

我有一组颜色,我希望选择反转。我有一个切换功能,它基本上根据数组为元素着色。如果我抛出一个反向变量,那么它会反转,但它会反转全局变量而不是局部变量。

var inc_colors = ['#000','#333','#888']; //global inc_colors

function toggleLegendColors(reverse){
  var reverse = reverse || false;
  var colors = inc_colors; //local colors
  if(reverse) colors.reverse(); //reverses inc_colors array as well as colors
  ...
}

如何在不更改全局数组的情况下获得反转的全局数组?

4

5 回答 5

14

您现在也可以使用 es6 扩展运算符来做到这一点:

let colors = [ ...inc_colors ].reverse()
于 2016-01-25T17:16:17.957 回答
13

由于没有人真正解释您遇到问题的原因,因此我将其添加到混合中。

当您将 javascript 中的数组或对象分配给变量时,它会分配对该数组/对象的引用。它不会复制数组/对象。因此,您将拥有两个变量,它们都指向同一个数组/对象,并且修改任何一个都会影响另一个(因为它们都指向同一个底层数据)。

所以,当你有这个时:

var inc_colors = ['#000','#333','#888']; //global inc_colors
var colors = inc_colors; //local colors

您现在所拥有的只是两个变量,它们都指向完全相同的数据。修改其中一个,相同的结果将通过另一个变量显示,因为它们指向相同的基础数据。

如果您想制作副本,则必须明确制作副本(javascript 不会自动为您完成)。对于数组,制作浅拷贝的最简单方法是这样的:

var newColors = Array.prototype.slice.call(inc_colors);

因此,在您的确切代码中,您可以像这样应用该副本:

var inc_colors = ['#000','#333','#888']; //global inc_colors

function toggleLegendColors(reverse){
  var reverse = reverse || false;
  var colors = Array.prototype.slice.call(inc_colors);  //local copy of the colors array
  if(reverse) colors.reverse(); //reverses inc_colors array as well as colors
  ...
}
于 2013-01-16T20:26:43.243 回答
11

只需使用Array.slice(安全方式)制作数组的副本:

var colors = Array.prototype.slice.call(inc_colors);
于 2013-01-16T19:48:44.143 回答
11

您可能会考虑的干净简单的方法,但涉及创建数组的新实例是

var arr_reverse=arr.slice(0).reverse();
于 2015-07-03T21:18:49.207 回答
1

简单的解决方案:

var inc_colors = ['#000','#333','#888']; //global inc_colors

function toggleLegendColors(reverse) {
  var colors = (inc_colors instanceof Array) ? inc_colors : [];
  colors = (!reverse) ? inc_colors.slice() : inc_colors.slice().reverse();
  // ...
}
于 2013-01-16T20:00:45.733 回答