..:: MX Studio Fóruns ::..: Números aleatórios & Array - JS - ..:: MX Studio Fóruns ::..

Jump to content

Publicidade




Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Números aleatórios & Array - JS

#1 User is offline   edergabriel 

  • Group: Membros
  • Posts: 17
  • Joined: 24-November 09

Posted 25 July 2011 - 10:39 PM

No código abaixo, a minha intenção era mostrar os cinco primeiros valores nesse array de forma aleatória. Não consegui, às vezes, ele falha no momento de não mostrar números que já foram selecionados e mostrar apenas as cinco primeiras seleções. Quem me ajudar ou tiver uma solução melhor, eu agradeço, quem não entendeu a minha dúvida é só perguntar.

No aguardo, obrigado!


<script language="JavaScript">
function random_imglink(){
	
  var myimages=new Array()
  
  var ry;
  
  var novory;
  
  myimages[0]="teste0"
  
  myimages[1]="teste1"
  
  myimages[2]="teste2"
  
  myimages[3]="teste3"
  
  myimages[4]="teste4"
  
  myimages[5]="teste5"
  
  myimages[6]="teste6"

	 for(x=0; x<7; x++){
		 
		ry=Math.floor(Math.random()*myimages.length)
		myimages[x] = ry

		novory = Math.floor(Math.random()*myimages.length)
	
		for(z=0; z<7; z++){
			
			if(myimages[z] == novory) {
	
			novory = Math.floor(Math.random()*myimages.length)
			z=0;
			}
	
			
		}
	myimages[x] = novory;
	document.write(myimages[x]+ "<br />")

		
	}
}

  random_imglink()
  </script>

0

#2 User is offline   xanburzum 

  • Group: Administrador
  • Posts: 2072
  • Joined: 04-November 08

Posted 13 August 2011 - 08:26 PM

ele gera algum erro ?
0

#3 User is offline   edergabriel 

  • Group: Membros
  • Posts: 17
  • Joined: 24-November 09

Posted 14 August 2011 - 12:08 AM

View Postxanburzum, on 13 August 2011 - 08:26 PM, said:

ele gera algum erro ?


Não tem erros, o problema é que ele não gera os cinco valores dentro dos sete sem repeti-los.
0

#4 User is offline   xanburzum 

  • Group: Administrador
  • Posts: 2072
  • Joined: 04-November 08

Posted 14 August 2011 - 01:17 PM

olha este exemplo, se tentar gerar uma matriz aleatória de números inteiros não repetidos,É mais fácil criar a primeira matriz, e então embaralhar.
função getRandomArray (min, max) {

var A = [];

while (max> = min) A.push (max -)

A.sort (function () {return 0,5 - Math.random ()});

Um retorno;

}


0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic


Similar Topics Collapse


Publicidade




1 User(s) are reading this topic
0 membro(s), 1 visitante(s) e 0 membros anônimo(s)