如何在Javascript中创建动态数组

How to create a dynamic array in Javascript?

本文关键字:创建 动态 数组 Javascript      更新时间:2023-10-27

我需要动态创建以下数组,例如:

var data = { point: [
              { x:5, y:8 },
              { x:8, y:10},
              ]};
 console.log(data.point[0].x);   // 5  n=0
 console.log(data.point[1].y);   // 10 n=1

在某个时刻,我的应用程序需要将数组扩展到2个以上的项(n=0,n=1)。请让我知道怎么做(即n=9)。

您可以使用Array.push方法将元素添加到数组中。

var point = {x:1,y:1};
data.point.push(point);

您可以使用类似以下代码的方法"push"

        var data = { point: [
                      { x:5, y:8 },
                      { x:8, y:10},
                      ]};
         console.log(data.point[0].x);   // 5  n=0
         console.log(data.point[1].y);   // 10 n=1
        data.point.push({x:4,y:3});
        console.log(JSON.stringify(data.point));

您可以这样做:

var data = {'points' : []};
function addPoint(x, y) {
    data.points.push({'x' : x, 'y' : y});
}
function getPoint(index) {
    return data.points[index];
}
addPoint(10, 20);
addPoint(5, 3);
var p = getPoint(1);
alert(p.x + ", " + p.y); //alerts => "5, 3"

这适用于任意数量的点。

更新

清除阵列

function clearPoints() {
    data.points = [];
}

更新2

如果你有一个简单的页面,这些小功能会正常工作。如果这种积分处理最终将成为一个更大系统的一部分,那么最好这样做:

var data = {
    'points' : [], 
    addPoint : function(x, y) {
        this.points.push({
            'x' : x, 
            'y' : y
        });
    }, 
    getPoint : function(index) {
        return this.points[index];
    }, 
    clearPoints : function() {
        this.points = [];
    }, 
    removePoint : function(index) {
        this.points.splice(index, 1);
    }
};

示例用法:

alert(data.points.length); // => 0
data.addPoint(1, 2);
data.addPoint(8, 12);
data.addPoint(3, 7);
alert(data.points.length); // => 3
var p = data.getPoint(2); //p = {x:3, y:7};
data.removePoint(1); 
alert(data.points.length); // => 2
data.clearPoints();
alert(data.points.length); // => 0

它可以让你的积分处理更干净,更容易使用和更新。

您可以按照说明使用push()函数,也可以使用索引向数组添加其他项,这在Google Style Guide中是首选项。后一种方法确实要求您有一个指向最后一个索引的指针。

请注意,由于为数组赋值比使用push()应该尽可能使用赋值。

for(var i=lastIndex; i < numOfNewPoints; i++){
    data.point[i] = {x:4, y:3};
}