JS函数返回一个包含对象的数组

JS function return an array containing objects

本文关键字:包含 一个 对象 数组 函数 返回 JS      更新时间:2024-04-09

我遇到了以下问题。对于一个项目,我得到了多个笛卡尔坐标(XYZ),我在一个函数中处理这些坐标。我试图让函数返回一个数组,其中包含保存在对象中的单独XYZ坐标(下面例子中的函数Coord(X,Y,Z))。

var test = Vertices();
var strTemp = "0 => X=" + test[0].X + " Y=" + test[0].Y + " Z=" + test[0].Z + "'n" +
              "1 => X=" + test[1].X + " Y=" + test[1].Y + " Z=" + test[1].Z + "'n" +
              "2 => X=" + test[2].X + " Y=" + test[2].Y + " Z=" + test[2].Z + "'n" +
              "3 => X=" + test[3].X + " Y=" + test[3].Y + " Z=" + test[3].Z + "'n" +
              "4 => X=" + test[4].X + " Y=" + test[4].Y + " Z=" + test[4].Z;
alert(strTemp);
// ************************* BELOW ARE THE FUNCTIONS ******************************************
function Coord(X, Y, Z) {
       /// <summary>
       /// Class that represents a cartesian coordinate
       /// </summary>
       /// <param name="X">X value</param>
       /// <param name="Y">Y value</param>
       /// <param name="Z">Z value</param>
    this.X = X;
    this.Y = Y;
    this.Z = Z;
};
function Vertices() {
       /// <summary>
    /// Function that collects the locations of all the selected vertices
    /// NOTE: This is a stripped down version of the original function
       /// in order to keep it readable.
       /// </summary>
    /// <returns type="">an array containing cartesian coordinates</returns>
    // create an instance of the Coord class for holding the cartesian coordinates
    var location = new Coord("", "", "");
    // initialize the array which will contain the locations
    var Result = [];
    // declarations of the index vars. There are two of them because of some logic I removed from this example ;)
    var j = 0;  // used as index for the array
    var i = 0;  // used as index for the loop
    // loop thru the selected vertices
    do {
        // fill the location object with the cartesian coordinates (currently represented as random values between 0 and 100)
        location.X = randomIntFromInterval(0, 100);
        location.Y = randomIntFromInterval(0, 100);
        location.Z = randomIntFromInterval(0, 100);
        // add the location object to the array
        Result.push(location);
        // confirm that the values are in the array
        alert(j + "/" + Result.length + "  X = " + Result[j].X + "  Y = " + Result[j].Y + "  Y = " + Result[j].Z);
        // increment the indices
        j++;
        i++;
    } while (i < 10);
    
    // return the array to the main program
    return Result;
}
function randomIntFromInterval(min, max) {
       /// <summary>
       /// generate random integers between a min and max value
       /// </summary>
       /// <param name="min">lowest possible value</param>
       /// <param name="max">highest possible value</param>
       /// <returns type="">integer</returns>
    //http://stackoverflow.com/questions/4959975/generate-random-value-between-two-numbers-in-javascript
    return Math.floor(Math.random() * (max - min + 1) + min);
}

在本例中,我有一个名为"Vertices()"的函数,该函数在本例中将生成一些随机坐标并将其保存在位置对象中(基于Coord(XYZ))。然后将位置对象添加到阵列中。数组返回到主程序。

"Vertices"内部的警报显示正确的值,但如果我尝试使用主程序中的值(请参阅strTemp),则所有值都是最后添加到数组中的值。

我希望有人能对此有所了解。。。

这是因为

var location = new Coord("", "", "");

不在循环中,因此,您保留对象的相同引用并更新所有索引

问题出在Verices函数中。在循环外创建Coords的单个实例,在循环内修改它并推送到数组。因此,您的Result数组包含指向同一个对象的10个链接。

为了解决这种情况,您应该在每个循环迭代中创建Coords的新实例:

var location;
do {
    location = new Coords("", "", "")
    // fill the location object with the cartesian coordinates (currently represented as random values between 0 and 100)
    location.X = randomIntFromInterval(0, 100);
    location.Y = randomIntFromInterval(0, 100);
    location.Z = randomIntFromInterval(0, 100);
    // add the location object to the array
    Result.push(location);
    // confirm that the values are in the array
    alert(j + "/" + Result.length + "  X = " + Result[j].X + "  Y = " + Result[j].Y + "  Y = " + Result[j].Z);
    // increment the indices
    j++;
    i++;
} while (i < 10);

更换

location = new Coords("", "", "")
// fill the location object with the cartesian coordinates (currently represented as random values between 0 and 100)
location.X = randomIntFromInterval(0, 100);
location.Y = randomIntFromInterval(0, 100);
location.Z = randomIntFromInterval(0, 100);
// add the location object to the array
Result.push(location);

带有:

Result.push(new Coords(randomIntFromInterval(0, 100), randomIntFromInterval(0, 100), randomIntFromInterval(0, 100)));

通过这种方式,您将使用新的随机值推送新实例。