2017-01-18 45 views
2

我正在製作一個功能,其中隨機索引被添加到使用for-loop的數組中,值必須始終不同,但不知何故有時(大約每調用10次函數)相同的值即使我試圖從answerId陣列中過濾相同的值,並將其餘值unique - 陣列和檢查過濾unique - 陣列和原始answerId - 陣列具有相同的長度,如果unique - 陣列長度低於unique - 陣列長度, answerId的值將被改變。但是即使在answerId -array中有相同的值,並且運行無法傳遞給for循環的其餘部分(這些for循環相當於一些hack代碼),但這些數組的長度始終相同。我做錯了什麼?對不起,如果我的英語技能不好。防止在數組中添加相同的隨機值

getJSONData(){ 

    var answerId = [null, null, null, null]; 
    var length = Object.keys(Company.person).length; 

    for(var i = 0; i <= answerId.length - 1; i++){ 
    answerId[i] = [Math.floor(Math.random() * length)] 

    } 

    let unique = Array.from(new Set(answerId)) 
    console.log(unique.length) 

    if (unique.length < answerId.length){ 
    for(var i = 0; i <= answerId.length - 1; i++){ 
     answerId[i] = [Math.floor(Math.random() * length)] 
    } 
    console.log("new values 1") 
    unique = Array.from(new Set(answerId)) 

    if (unique.length < answerId.length){ 
     for(var i = 0; i <= answerId.length - 1; i++){ 
     answerId[i] = [Math.floor(Math.random() * length)] 
     } 
     console.log("new values 2") 
     unique = Array.from(new Set(answerId)) 

     if (unique.length < answerId.length){ 
     for(var i = 0; i <= answerId.length - 1; i++){ 
      answerId[i] = [Math.floor(Math.random() * length)] 
     } 
     console.log("new values 3") 
     unique = Array.from(new Set(answerId)) 

     if (unique.length < answerId.length){ 
      for(var i = 0; i <= answerId.length - 1; i++){ 
      answerId[i] = [Math.floor(Math.random() * length)] 
      } 
      console.log("new values 4") 
     } 
     } 
    } 
    } 

    var personArray = [Company.person[answerId[0]].firstName + ' ' + Company.person[answerId[0]].lastName, Company.person[answerId[1]].firstName + ' ' + Company.person[answerId[1]].lastName, Company.person[answerId[2]].firstName + ' ' + Company.person[answerId[2]].lastName, Company.person[answerId[3]].firstName + ' ' + Company.person[answerId[3]].lastName]; 
    return personArray; 
} 
+0

什麼'JSON-indexes'? [JSON](http://json.org/)是一個字符串,代表序列化數據。 –

+0

我刪除了Json提到的問題是否令人困惑。 –

+0

您也可以添加數據。 –

回答

1

您可以直接使用Setsize屬性來檢查結果集的所需大小。

var array = [0, 1, 42, 17, 22, 3, 7, 9, 15, 35, 20], 
 
    unique = new Set; 
 

 
while (unique.size < 4) { 
 
    unique.add(Math.floor(Math.random() * array.length)); 
 
} 
 

 
console.log([...unique]); // indices

否則,你可以使用一個哈希表。

var array = [0, 1, 42, 17, 22, 3, 7, 9, 15, 35, 20], 
 
    unique = {}, 
 
    id = [], 
 
    i; 
 

 
while (id.length < 4) { 
 
    i = Math.floor(Math.random() * array.length); 
 
    if (!unique[i]) { 
 
     id.push(i); 
 
     unique[i] = true; 
 
    } 
 
} 
 

 
console.log(id);

+0

我嘗試使用Set對象,但它不起作用,它中有相同的值。 '.add'可以工作,但'.has'不能。我堅信,React-Native不完全支持Set。 –

+0

「大小」是否有效?我不使用'has'。 –

+0

尺寸確實有效。但即使值不唯一,它也會始終返回4。 –

1

正如我理解你的問題,你想從數組中獲得N個隨機值,值應該是唯一的。你剛剛洗牌你的數組,並從中獲得第一個N值。