Javascript 数组推送替换同一数组中的前一个元素
Javascript Array Push Replaces Previous Element in The same Array
我正面临这个问题,我的 randomPoints
数组元素正在被推送方法替换。
Here is the output of my Console
我不知道为什么会这样,但如果我不使用 randomPoint.add
,它不会替换并且工作正常。
randomPoint.add
重新调整相同的 Vector 对象,就像 return 没有它一样。
var hw
var center
var randomPoints = []
var pointWidth = 20
var points = 300
centerCircleWidth = 300;
pointsOffset = 10
function setup(){
hw = createVector(600,500)
createCanvas(hw.x,hw.y)
center = createVector(hw.x/2,hw.y/2)
var randomPoint = createVector(0,0)
randomPoints.push(randomPoint)
randomPoint = p5.Vector.fromAngle(-radians(120), random(centerCircleWidth/2-pointWidth,centerCircleWidth/2-pointsOffset))
randomPoints.push(randomPoint)
console.log(randomPoint)
randomPoint = randomPoint.add(p5.Vector.fromAngle(radians(60), random(pointsOffset,2*pointsOffset)))
// this here replaces the last element of array by itself and add another element of same type.
randomPoints.push(randomPoint)
console.log(randomPoint)
console.log(randomPoints)
}
function draw(){
translate(center.x, center.y)
background(51);
strokeWeight(0)
fill(255)
ellipse(0,0, centerCircleWidth, centerCircleWidth)
for(i=0;i<randomPoints.length;i++){
fill(10)
ellipse(randomPoints[i].x,randomPoints[i].y,pointWidth,pointWidth)
}
}
您的问题看起来是对象引用问题。第三个 push
并未替换数组中的前一个元素,但您正在更新数组所持有的 reference,因此正在更新数组中的元素。
如果删除第三个 push
,您会看到数组中的第二个项目仍会更新。
您需要做的是创建 randomPoint
的副本然后对其进行更改,或者创建一个新变量。
看看 this SOF 的回答,应该会更清楚。
我正面临这个问题,我的 randomPoints
数组元素正在被推送方法替换。
Here is the output of my Console
我不知道为什么会这样,但如果我不使用 randomPoint.add
,它不会替换并且工作正常。
randomPoint.add
重新调整相同的 Vector 对象,就像 return 没有它一样。
var hw
var center
var randomPoints = []
var pointWidth = 20
var points = 300
centerCircleWidth = 300;
pointsOffset = 10
function setup(){
hw = createVector(600,500)
createCanvas(hw.x,hw.y)
center = createVector(hw.x/2,hw.y/2)
var randomPoint = createVector(0,0)
randomPoints.push(randomPoint)
randomPoint = p5.Vector.fromAngle(-radians(120), random(centerCircleWidth/2-pointWidth,centerCircleWidth/2-pointsOffset))
randomPoints.push(randomPoint)
console.log(randomPoint)
randomPoint = randomPoint.add(p5.Vector.fromAngle(radians(60), random(pointsOffset,2*pointsOffset)))
// this here replaces the last element of array by itself and add another element of same type.
randomPoints.push(randomPoint)
console.log(randomPoint)
console.log(randomPoints)
}
function draw(){
translate(center.x, center.y)
background(51);
strokeWeight(0)
fill(255)
ellipse(0,0, centerCircleWidth, centerCircleWidth)
for(i=0;i<randomPoints.length;i++){
fill(10)
ellipse(randomPoints[i].x,randomPoints[i].y,pointWidth,pointWidth)
}
}
您的问题看起来是对象引用问题。第三个 push
并未替换数组中的前一个元素,但您正在更新数组所持有的 reference,因此正在更新数组中的元素。
如果删除第三个 push
,您会看到数组中的第二个项目仍会更新。
您需要做的是创建 randomPoint
的副本然后对其进行更改,或者创建一个新变量。
看看 this SOF 的回答,应该会更清楚。