0

I am trying to simulate data to a function that would usually receive a JSON parsed data structure. When running this I get an error TypeError: can't convert undefined to object here: data.targets[i] = {

What am I doing wrong?

function SendFakeTargets(maxTargets, interval) {
    var data = {};
    data.timestamp = +new Date;

    var time = data.timestamp * 0.0005;
    var x = Math.sin(time) * 192 + 256;
    var y = Math.cos(time * 0.9) * 192 + 256;

    console.log(x, y);

    for (var i = 0; i < maxTargets; i++) {
        console.log(i);

        data.targets[i] = { //error is here
            id: i,
            x: x + (i * 10),
            y: y + (i * 10)
        };
    }

    HandleTargetData(data);

    setTimeout("SendFakeTargets("+maxTargets+", "+interval+")", interval);
}
2
  • var data = {targets:[], timestamp:Number(new Date)}; Commented Oct 4, 2012 at 13:31
  • please don't use a string as the callback parameter to setTimeout ... Commented Oct 4, 2012 at 13:35

3 Answers 3

4

you should previously declare

data.targets = [];

before using data.targets[i] inside the loop, otherwise data.targets is undefined. In a shorter way you could write

var data = {
    timestamp : +new Date,
    targets   : []
};

And as a side note, never use strings in setTimeout/Interval. Do instead

 setTimeout(function() {
      SendFakeTargets(maxTargets, interval);
 }, interval);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, what is the reasoning behind using a function call as opposed to a string? Is it solely to avoid an eval or is there another reason?
yep, it is to mainly avoid an eval (and for better readability - especially of arguments - imho)
1

I think you need to initialize the targets array before using it, as it is undefined. You are defining data as

var data = {}

which is declaring it as an empty object, anything else that you're doing with it is added on the fly - arrays need to be initialized before you can call any index in them. I believe what you need to do is:

var data = { targets: [] }

Comments

0

You never declared "data.targets" as a an object so javascript doesn't know how to assign anything to it.

At the top of your code just define "targets":

data.timestamp = +new Date;
data.targets = {} or [];
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.