创建一个javascript对象,然后通过for循环填充一个数组

Create a javascript object and then fill an array through a for loop

本文关键字:一个 for 循环 数组 填充 对象 javascript 创建 然后      更新时间:2023-09-26

我对javascript非常陌生,所以请耐心等待。:)我有以下对象

var obj= {
    x: 0,
    y: 0
};

我想创建一个函数,从用户那里获取x,y,并将它们存储到一个数组中。所以本质上我想要一个数组来存储"obj"对象。

var arr=[];var i;

对于(i=0;i<10;i++){arr[i]=新obj(x,y);}

我甚至不确定我是否已经开始了正确的方式。那么,如何用这样的对象填充数组呢?

arr=[obj1,obj2,obj3,obj4];

谢谢。。

这是正确的,如果你想使用新的运算符,请使用函数。

var obj = function(a,b) {
 this.x = a;
 this.y = b;
 this.Sum = function(){
     return this.x + this.y;
 };
};
var arr = [],sumarr=[]; var i;
for(i=0; i<10; i++) 
{ 
 arr[i] = new obj(i,i+1);
 sumarr[i] = arr[i].Sum();
}

为了更好地理解这个概念,我建议[http://zeekat.nl/articles/constructors-considered-mildly-confusing.html]。

您可以执行类似t的操作http://jsfiddle.net/naeemshaikh27/y5jaduuf/1/

 var arr = []; var obj={};
    $("#addToArray").click(function(){
        obj.x= $("#x").val();
        obj.y=$("#y").val();

        arr.push(obj);

});
// create a constructor for our Obj
function Obj(x, y) {
    this.x = x;
    this.y = y;
}
/* fills array with those objects */
// create an array
var objs = [];
// fill the array with our Objs
for (var i = 0; i < 10; i++) {
    objs.push(new Obj(i, i));
}
// and show the result
var msg = "";
for (var i = 0; i < objs.length; i++) {
  msg += objs[i].x + ":" + objs[i].y + ''n';
}
/* now */
alert(msg);

http://cssdeck.com/labs/elm2uj00

如果你对javascript非常陌生,我建议你读一本关于javascript的好书。例如David Flanagan的:JavaScript最终指南您现在和将来都有很多问题的答案。这是我能建议的最好的方法。Stackloverlow不会在当前阶段为您提供太多帮助。这是我的看法