简体   繁体   English

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

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

I am extremly new in javascript so please be patient.:) I have the following object 我是javascript的新手,所以请耐心等待。:)我有以下对象

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

I want to create a function that will take x,y from the user and store them to an array. 我想创建一个函数,该函数将从用户处获取x,y并将其存储到数组中。 So essensialy i want an array to store "obj" objects. 因此,本质上来说,我想要一个数组来存储“ obj”对象。

var arr = []; var arr = []; var i; var i;

for(i=0; i<10; i++) { arr[i] = new obj(x, y); for(i = 0; i <10; i ++){arr [i] =新的obj(x,y); } }

I am not even sure if i have started the correct way. 我什至不确定我是否已经开始正确的方法。 So how can i fill my array with objects like this? 那么如何用这样的对象填充数组?

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

Thank you.. 谢谢..

Its is correct expect if u want to use the new operator use the function. 如果您要使用新的运算符,请使用该函数,这是正确的期望。

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();
}

For better understanding of the concept I recommend [ http://zeekat.nl/articles/constructors-considered-mildly-confusing.html] . 为了更好地理解该概念,我建议[ http://zeekat.nl/articles/constructors-considered-mildly-confusing.html]

you can do something like t http://jsfiddle.net/naeemshaikh27/y5jaduuf/1/ 您可以执行以下操作: 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 http://cssdeck.com/labs/elm2uj00

If you're extremely new in javascript, I would advise you read good book about javascript. 如果您在javascript方面是新手,建议您阅读有关javascript的好书。 For example David Flanagan's: JavaScript The Definitive Guide There are many answers of the questions that you have now and will. 例如, David Flanagan的:JavaScript权威指南现在和将来都会有许多问题的答案。 It's best way I can suggest. 我建议的最好方法。 Stackoverlow will not provide you much help on your current stage. Stackoverlow在当前阶段不会为您提供太多帮助。 That's my opinion 那是我的意见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM