splice正在影响以前复制的变量 [英] splice is affecting previously copied variables

查看:86
本文介绍了splice正在影响以前复制的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在javascript中按值复制数组

我有一个有趣的JavaScript问题。我复制一个数组变量只对副本进行修改,然后拼接副本删除一个元素。但原始数组变量受拼接影响 - 好像副本是'按引用复制':

i have a funny problem with javascript. i copy an array variable to make modifications on the copy only, then splice the copy to delete an element. however the original array variable is affected by the splice - as if the copy was a 'copy by reference':

window.onload = function() {
  var initial_variable = ['first', 'second', 'third'];
  var copy_initial_variable = initial_variable;
  copy_initial_variable.splice(0, 1);
  alert('initial variable - ' + initial_variable);
};
//output: initial variable - second,third

首先,这是javascript的故意行为还是一个bug?

firstly, is this intentional behaviour for javascript or is it a bug?

其次,如何制作数组副本并删除副本中的一个元素但不是原始元素?

and secondly, how can i make a copy of an array and delete an element in the copy but not in the original?

有一件事让我觉得上面可能是一个javascript错误,这个行为只发生在数组而不是用整数。例如:

one thing which makes me think that the above may be a javascript bug is that this behaviour only happens with arrays and not with integers. for example:

window.onload = function() {
  var initial_variable = 1;
  var copy_initial_variable = initial_variable;
  copy_initial_variable = 2;
  alert('initial variable - ' + initial_variable);
};
//output: initial variable - 1

如果行为一致那么这应该是输出 2 因为作业大概是通过参考?

if the behaviour were consistent then this ought to output 2 since the assignment would presumably be by reference?

推荐答案

这个绝不是一个错误,而是一个非常普遍的误解。让我们看看当我说

This is in no way a bug, but a very common misunderstanding. Let's see what happens when I say

var a = b;

整数和其他javascript原语(如浮点数和布尔值)是按值分配。
这意味着 b 所具有的任何值都将被复制到 a 。对于计算机,这意味着将 b 引用的内存部分复制到 a 引用的内存中。这就是你期望的行为。

Integers and other javascript primitives, like floats and booleans, are "assigned by value". Which means that whatever value b has is going to be copied to a. To the computer, it means having the part of memory that b references copied to the memory that a references. That's the behavior you were expecting.

当数组和其他对象(以及 new Object()的后代 call)就像这样使用,有一个参考副本。这意味着 a 的值现在引用了 b 的值, b 引用的内存不会被复制或修改。因此,在写作时

When arrays and other objects (and "descendants" of a new Object() call) are used like that, there is a copy by reference. Meaning that the value of a now references the value of b, the memory that b references isn't copied or modified. Thus, when writing

a = [1,2,3];
b = a;

b a 可以互换。他们引用相同的内存地址。要实现您的目标,请使用

b and a become interchangeable. They're referencing the same memory address. To achieve what you're trying to do, use

var copy_initial_variable = initial_variable.slice(0);

阅读 JavaScript是否通过引用传递?以获取更多信息。

这篇关于splice正在影响以前复制的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆