2013-12-14 74 views
0

我知道這是一個簡單的任務,但我正在學習JavaScript。我想抓住FOR循環中的第一個項目,並抓住第二個項目。有沒有辦法做到這一點。我只需要三個隨機數組。在FOR循環中選擇特定項目

/** 
* Created by the JavaScript Development Team 
* Class: PWA 
* Goal: Goal7 
*/ 

(function() { 
    var names = ["walker", 'marisa', 'annie', 'gizmo', 'marvin']; 
    function shuffle(o) { //v1.0 
     for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); 
     return o; 
    }; 
    myArray = shuffle(names); 
    console.log(myArray); 
    var Person = function (name) { 
     this.name = name; 
     console.log(this.name); 
     //  for(i=0; i< names.length; i++){ 
     //   var person =[new Person(names[i])]; 
     //  } 
    }; 
    console.log('hello'); 
    var i = 0; 
    var length = myArray.length = 3 
    while (i < length) { 
     //console.log(myArray[i]); 
     var person = new Person(myArray[i]); 
     //  var person = [new Person(names[i])]; 
     i++; 
    } 
})(); 

回答

0

您的意思是這樣的?

for (var i=0; i++; i < names.length; i++) { 
     if (i==1) { 
      //grab 
     } 
     else if (i==2) { 
      //grab 
     } 
     else { 
      //Do more 
     } 
} 

甚至更​​好:names[0]是陣列中的第一個和names[1]是第二個。沒有必要循環,如果這是你需要的。

0

你的意思是這樣

for(var i = 2; i >=0; i--) { 
    new Person(myArray[i]); 
} 

但說實話,你爲什麼需要循環,如果你知道你有多少項目要與項目已被隨機?在while循環

0

使用斷點:

(function() { 
     var names = ["walker", 'marisa', 'annie', 'gizmo', 'marvin']; 
     function shuffle(o) { //v1.0 
      for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); 
      return o; 
     }; 
     myArray = shuffle(names); 
     console.log(myArray); 
     var Person = function (name) { 
      this.name = name; 
      console.log(this.name); 
      //  for(i=0; i< names.length; i++){ 
      //   var person =[new Person(names[i])]; 
      //  } 
     }; 
     console.log('hello'); 
     var i = 0; 
     var length = myArray.length = 3 
     while (i < length) { 
      //console.log(myArray[i]); 
      var person = new Person(myArray[i]); 
      //  var person = [new Person(names[i])]; 
       if(i == 2){ break; } // <== 
      i++; 
     } 
    })(); 
0

我覺得你是在這個有點複雜。如果你只是想要三個隨機的名字,你爲什麼要打亂所有的名字?我爲你寫了一些代碼,我認爲它更清晰一些。

(function() { 

    var people = ['walker', 'marisa', 'annie', 'gizmo', 'marvin']; 

    var random_people_to_get = 3; 
    var random_people = []; 

    var Person = function (name) { this.name = name; }; 


    for(var i = 0; i < random_people_to_get; i++){ 

     // Grabbing a random name from people and removing it! 
     var random_name = people.splice(Math.floor(Math.random() * people.length), 1)[0]; 

     // Make the random_name into a person and put it into the random_people array! 
     random_people.push(new Person(random_name)); 

    } 

    console.log(random_people); 

})(); 

如果你想使用slice在用自己的方式堅持可以使一個數組與前三個項目。就像:

var firstThreeRandomNames = myArray.slice(0, 3);