简体   繁体   English

JavaScript变量声明问题

[英]Javascript Variable Declaration Issue

var Stars = new Array(1,2,3,4,5,6,7,8,9,10);
var StarsX = new Array(451,455,460,470,490,100,160,220,280,300);
var StarsY = new Array(451,455,460,470,490,480,390,330,200,120);
var Starsm = Stars
var StarsmX = StarsX
var StarsmY = StarsY

//just shows the output of the variables in a text field
function contpost(){Tfield.innerHTML=Stars + "<br/>" + StarsX + "<br/>" + StarsY + "<br/>" + Starsm + "<br/>" + StarsmX + "<br/>" + StarsmY;}

//cycles through the "for" loop and posts the variables
function newpost(){
for (var i=0;i<Stars.length;i++){
    StarsmX[i] = StarsX[i] + 10;
    StarsmY[i] = StarsY[i] + 10;
    }
contpost()
}


var Tfield= (This is the text field)
var canv_one= (This is a canvas in my document)
canv_one.addEventListener('click', newpost);

If I run this code (Firefox 9), the if/then loop adds 10 to both the "mX" variable and the "X" variable. 如果我运行此代码(Firefox 9),则if / then循环会将10分别添加到“ mX”变量和“ X”变量中。

I now know approximately how it does it. 我现在大概知道它是如何做到的。 It's simply because I set them equal early on. 这仅仅是因为我尽早将它们设置为相等。 When I substitute this in the declarations, it works properly: 当我在声明中替换它时,它可以正常工作:

var Starsm = new Array()
var StarsmX = new Array()
var StarsmY = new Array()

What I don't understand is why javascript is doing this. 我不明白的是为什么javascript会这样做。 It seems logical to me that if you set them equal once, during the global declaration, they will not re-equate later on (and do it backward, at that. I never set StarsX equal to StarsmX.) 在我看来,如果在全局声明期间将它们设置一次相等,那么在以后它们将不会重新相等(并且这样做会反向进行。我从未将StarsX设置为等于StarsmX。)

I'm pretty sure this means I'm not understanding some kind of basic functionality of Javascript, and that worries me. 我很确定这意味着我不了解Javascript的某种基本功能,这让我感到担忧。

Can anybody help? 有人可以帮忙吗?

It isn't adding anything to the variable. 它没有向变量添加任何内容。 It's adding to the Array, and both variables reference the same Array object. 它添加到Array中,并且两个变量都引用相同的Array对象。

This is because in JavaScript you only get to hold a reference to an object, not the object itself. 这是因为在JavaScript中,您只能持有对对象的引用 ,而不是对象本身。 So the reference to the Array is the value being copied, not the Array. 因此,对数组的引用是要复制的值,而不是数组。

If you wanted a shallow clone of the Array, use slice() . 如果您想要Array的浅表克隆,请使用slice()

var Starsm = Stars.slice()
var StarsmX = StarsX.slice()
var StarsmY = StarsY.slice()

Or just do as you said, and create empty Arrays. 或者按照您所说的做,然后创建空数组。

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

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