javascript - 将数组作为参数粘贴到函数 Javascript 时保持数组不变的方法

标签 javascript arrays

我有一个对象数组 A

我有 2 个不同的绘图函数,它们以自己的方式完全改变了 A。 我想保持 A 不变。是否有最佳做法如何做到这一点?我目前的解决方案有点不自然:

var A;//Should stay the same always

drawGraphX(A){
//Modifying A here to draw but I would like the original A to stay the same
B=JSON.parse(JSON.stringify(A));
//So I do it with B
}

drawGraphY(A){
//Modifying A here to draw
B=JSON.parse(JSON.stringify(A));
//So I do it with B
}

最佳答案

我怀疑这里的真正答案是您根本不应该更改函数内的数据!

让我们假设 A 是一个用于图表的 x/y 点数组

var A = [{x:1,y:1},{x:2,y:2},{x:3,y:3}];

而您的函数只需要 x - 您是这样做的吗:

function drawGraphX(A){
   for(var i=0;i<A.length;i++)
      A[i] = A[i].x; 

   // now draw the graph
}

在上面的示例中,是的,您将更改 A 的源,因为您刚刚将引用传递给函数并更新了该引用数组的元素。这是不好的做法,你应该做的是:

function drawGraphX(A){
   var data = A.map(function(e){
       return e.x;
   });

   // data is an array of just the x values
}

关于javascript - 将数组作为参数粘贴到函数 Javascript 时保持数组不变的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41573059/

相关文章:

javascript - 难以将事件处理程序附加到动态生成的模态窗口元素

javascript - 如何设置 .shown() div 按钮的样式?

php - javascript 文件没有被缓存?

python - 通过 numpy 坐标数组索引 numpy 数组

Java 优化字符串与字符数组

javascript - createShadowRoot 与 attachShadow

javascript - 有什么方法可以通过单击外部来关闭 Angular UI 工具提示吗?

python - 保存 readlines 数组需要 RAM 吗?

c - "Expected expression before ' { ' token"

c - 将多维数组传递给函数