簡體   English   中英

Javascript數組推式替換同一數組中的前一個元素

[英]Javascript Array Push Replaces Previous Element in The same Array

我正在面對這個問題,我的randomPoints 數組元素已被push方法取代 這是我的控制台的輸出

我不知道為什么會這樣,但是如果我不使用randomPoint.add ,它就不會替換並且不能正常工作。

randomPoint.add重新調整相同的Vector對象,就像沒有它時將返回的一樣。

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不會替換數組中的前一個元素,但是您正在更新數組所保存的引用 ,因此正在更新數組中的元素。

如果刪除了第三次push ,您將看到數組中的第二項仍將被更新。

您需要做的是創建randomPoint的副本,然后對其進行更改,或者創建一個新變量。

看一下這個 SOF答案, 答案應該更清楚。

嘗試:

  let randomPoint_1 = createVector(0,0) randomPoints.push(randomPoint_1) let randomPoint_2 = p5.Vector.fromAngle(-radians(120) // .... 
等等..
否則,您將其他元素推入相同的元素,女巫還將更改之前推入的其他出現值,因為JS對象始終由指針使用,並且不會被復制。 使用Object.assign或cloneNode ...等復制您擁有的任何對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM