質問

Quick question, I'm pretty new to JavaScript, and I will undoubtedly learn a lot from this project. So I propose a question (which could well be a silly one), my question is:

I am planning to build a web application that dynamically generates shapes from either Raphael or Joint.js both of which are very similar, by dynamic I mean that there will be an undefined amount of objects to draw until the user enters, for example the amount of objects they wish to draw - so here's some code to reinforce my question:

var erd = Joint.dia.erd;
Joint.paper("world", 800, 250);

var e1 = erd.Entity.create({
    rect: {
        x: 220,
        y: 70,
        width: 100,
        height: 60
    },
    label: "Entity"
});

So, I've created a object of type rectangle, but here is what I want to know - can I do this:

var erd = Joint.dia.erd;
Joint.paper("world", 800, 250);
int x, y;
for (int i = 0; i < numOfUserDefObjects; i++) {
    var e1 = erd.Entity.create({
        rect: {
            x: x,
            y: y,
            width: 100,
            height: 60
        },
        label: "Entity"
        x + 20;
        y - 40;
    });
}

All is what puzzles me is, the var e1. If there are 2 objects to be created, will the first object created in the loop be erased/deleted/overwritten from my SVG/Canvas whenever the loop iterates through the loop for a second time/to create the second object?

A little insight to this would be greatly appreciated! Again, lack JavaScript experience but that'll change.

Thanks, again.

役に立ちましたか?

解決

In javascript, local variables declared with var have function scope. That means there is exactly one copy of that local variable per function. So, in your second code block, there is only one copy of the variable e1 and the for loop is assigning different values to it in every iteration.

You can do what you are doing, but e1 will only have one value in it when you're done and that value will be whatever the last iteration of the for loop assigned to it.

I don't know exactly what you're trying to accomplish, but you could create an array of your objects like this:

var erd = Joint.dia.erd;
Joint.paper("world", 800, 250);
var x = 0, y = 0;
var objs = [];
for (var i = 0; i < numOfUserDefObjects; i++) {
    objs.push(erd.Entity.create({
        rect: {
            x: x,
            y: y,
            width: 100,
            height: 60
        },
        label: "Entity"
    }));
    x += 20;
    y -= 40;
}
// objs now contains an array of the created objects

Note: I also initialized x and y, fixed the declarations to use var instead of int and correctly increment and decrement x and y in the for loop. You had a lot of syntax errors in the code you posted.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top