1

"Working" example is here (this script deals with the triangle animation)

http://movable.pagodabox.com/

full code here: http://pastebin.com/rgPNxHgJ

This question is mainly about the proper syntax. I have the following:

shape.transitionTo({
     offset: {
          x: 10,
          y: 10
     }
})

What I want to do is have "x" and "y" be randomly selected from an array, for example:

    movementIn = [
        {x: 34, y: 66},
        {x: -34, y: -66}
    ],

    shape.transitionTo({
        offset: movementIn[Math.floor(Math.random() * movementIn.length)],
    });

But this doesn't seem to be working... it seems to be only choosing the first item every time. Am I doing something wrong here?

how do I select a random X and Y pair and insert it into the "offset" parameter?

Thanks!

HandiworkNYC.com
  • 10,914
  • 25
  • 92
  • 154
  • Syntax looks correct ... maybe the problem is you're initializing the value rather than getting a new value every time? Hard to tell without the context. – McGarnagle Aug 05 '12 at 01:33
  • 1
    The `],` looks out of place (in both places, a syntax error in one and a semantic error in the other). Please paste a [minimal] test-case on jsfiddle [focusing on the specific question] and the *exact* code being used .. –  Aug 05 '12 at 01:37
  • http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array –  Aug 05 '12 at 01:54

1 Answers1

1

"Works for me"

arr = ["a","b","c"]
res = ""
for (i = 0; i < 10; i++) {
   res += arr[Math.floor(Math.random() * arr.length)]
}
alert(res)

Do note that this is not the "correct" way to pick one item as the distribution is slightly skewed ..

There are some syntax and semantical issues with the code in the question that should be explored:

{
   although_SomeBrowsers: "accept me",
   iAmAnInvalidLiteral: "BecauseThereIsAnExtraComma",
}

I feel trolled, here you go:

arr = [{x:1,y:-1},{x:2,y:-2},{x:3,y:-3}]
for (i = 0; i < 10; i++) {
   AN_OBJECT = arr[Math.floor(Math.random() * arr.length)]
   // do whatever you want to do with what AN_OBJECT names
   alert("x: " + AN_OBJECT.x + " y: " + AN_OBJECT.y)
}
  • Thanks pst, but this isn't the same... in my array, there are two pairs, where each array item is an X and Y pair... I just think I'm not doing it quite right! – HandiworkNYC.com Aug 05 '12 at 01:45
  • @j-man86 It is exactly the same. It doesn't matter what *object* is selected; there is still a singular object selected. Change `res = ""` to `res = []` and `res +=` to `res.push` and then you have an array of your arbitrary object. My point is the code posted *Works Here*, insofar as the errors in it are fixed. The idea is correct. –  Aug 05 '12 at 01:45
  • Maybe im not asking the right question: how do I select a random X and Y pair and insert it into the "offset" parameter? – HandiworkNYC.com Aug 05 '12 at 01:47