Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [JS] Losowy element tablicy
Dominator
post 16.04.2013, 21:04:33
Post #1





Grupa: Zarejestrowani
Postów: 565
Pomógł: 15
Dołączył: 11.10.2010

Ostrzeżenie: (20%)
X----


Czemu nie działa?

  1. var messages = new Array();
  2. var messages[1]="Ada";
  3. var messages[2]="Adela";
  4. var messages[3]="Adelajda";
  5. var messages[4]="Adriana";
  6. var messages[5]="Adrianna";
  7. var messages[6]="Agata";
  8. var messages[7]="Agnieszka";
  9. var messages[8]="Agrypina";
  10.  
  11. function getMessage() {
  12. return messages[Math.floor(Math.random() * messages.length)];
  13. }
Go to the top of the page
+Quote Post
Szymciosek
post 16.04.2013, 21:23:05
Post #2





Grupa: Zarejestrowani
Postów: 1 168
Pomógł: 126
Dołączył: 5.02.2010
Skąd: Świdnica

Ostrzeżenie: (0%)
-----


Kod
var messages = new Array();
messages[1]="Ada";
messages[2]="Adela";
messages[3]="Adelajda";
messages[4]="Adriana";
messages[5]="Adrianna";
messages[6]="Agata";
messages[7]="Agnieszka";
messages[8]="Agrypina";


console.log(messages[Math.floor(Math.random() * messages.length)]);


Sprawdzałem to sobie w konsoli, dlatego lekko przerobione
Go to the top of the page
+Quote Post
PrinceOfPersia
post 16.04.2013, 21:39:51
Post #3





Grupa: Zarejestrowani
Postów: 717
Pomógł: 120
Dołączył: 18.04.2009

Ostrzeżenie: (0%)
-----


Cytat
Czemu nie działa?

bo deklarujesz kilka razy tę samą zmienną (jedno var powinno być, a nie kilka). Poza tym - indeksy tablic w JS (jak i wielu innych językach) zaczynają się od zera, a nie od jedynki.



--------------------
Go to the top of the page
+Quote Post
Majcon
post 16.04.2013, 23:07:57
Post #4





Grupa: Zarejestrowani
Postów: 113
Pomógł: 1
Dołączył: 27.11.2012
Skąd: Sieradz

Ostrzeżenie: (0%)
-----


Kod
var messages = new Array('Ada', 'Adela', 'Adelajda', 'Adrianna', 'Agata', 'Agnieszka', 'Agrypina');
Go to the top of the page
+Quote Post
PrinceOfPersia
post 17.04.2013, 07:45:55
Post #5





Grupa: Zarejestrowani
Postów: 717
Pomógł: 120
Dołączył: 18.04.2009

Ostrzeżenie: (0%)
-----


ano. Albo jeszcze prościej, wywalmy to Array:
Kod
var messages = ['Ada', 'Adela', 'Adelajda', 'Adrianna', 'Agata', 'Agnieszka', 'Agrypina'];


--------------------
Go to the top of the page
+Quote Post
pyro
post 17.04.2013, 09:45:24
Post #6





Grupa: Zarejestrowani
Postów: 2 148
Pomógł: 230
Dołączył: 26.03.2008

Ostrzeżenie: (0%)
-----


  1. function getRandomInt(min, max) {
  2. return Math.floor(Math.random() * (max - min + 1)) + min;
  3. }
  4.  
  5. var randomIndex = getRandomInt(0, (messages.length-1));
  6.  
  7. console.log(messages[randomIndex]);


--------------------
ET LINGUA EIUS LOQUETUR IUDICIUM
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 25.07.2025 - 10:47