简体   繁体   English

Javascript从数组中选择一个随机对象集

[英]Javascript select a random object set from array

"Working" example is here (this script deals with the triangle animation) “工作”示例在此处(此脚本处理三角形动画)

http://movable.pagodabox.com/ http://movable.pagodabox.com/

full code here: http://pastebin.com/rgPNxHgJ 完整代码在这里: 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: 我想做的是从数组中随机选择“ x”和“ y”,例如:

    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? 如何选择一个随机的X和Y对,并将其插入“偏移”参数中?

Thanks! 谢谢!

"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)
}

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

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