2017-09-11 67 views
-1

我有一些Javascript代碼有變量1-9,我覺得可以更有效地寫入?使用某種循環?更有效的方式來列出在Javascript中類似的多個變量?

這是我看起來很潦草,低效的代碼片段。有沒有更好的方法來循環連續的變量?

編輯:

最後我只是用for循環來創建每個變量獨立的數組:

 var num = [] 
 
     for (var i = 0; i < imgAr.length; ++i) { 
 
     num[i] = Math.floor(Math.random() * imgAr.length) 
 
     } 
 
     var img = [] 
 
     for (var j = 0; j < imgAr.length; ++j) { 
 
     img[j] = imgAr[ num[j] ] 
 
     } 
 
     var imgStr = [] 
 
     for (var k = 0; k < imgAr.length; ++k) { 
 
     imgStr[k] = '<img src="' + path + img[k] + '" alt = "">' 
 
     }

var num1 = Math.floor(Math.random() * imgAr.length); 
 
    var num2 = Math.floor(Math.random() * imgAr.length); 
 
    var num3 = Math.floor(Math.random() * imgAr.length); 
 
    var num4 = Math.floor(Math.random() * imgAr.length); 
 
    var num5 = Math.floor(Math.random() * imgAr.length); 
 
    var num6 = Math.floor(Math.random() * imgAr.length); 
 
    var num7 = Math.floor(Math.random() * imgAr.length); 
 
    var num8 = Math.floor(Math.random() * imgAr.length); 
 
    var num9 = Math.floor(Math.random() * imgAr.length); 
 
    var img1 = imgAr[ num1 ]; 
 
    var img2 = imgAr[ num2 ]; 
 
    var img3 = imgAr[ num3 ]; 
 
    var img4 = imgAr[ num4 ]; 
 
    var img5 = imgAr[ num5 ]; 
 
    var img6 = imgAr[ num6 ]; 
 
    var img7 = imgAr[ num7 ]; 
 
    var img8 = imgAr[ num8 ]; 
 
    var img9 = imgAr[ num9 ]; 
 
    var imgStr1 = '<img src="' + path + img1 + '" alt = "">'; 
 
    var imgStr2 = '<img src="' + path + img2 + '" alt = "">'; 
 
    var imgStr3 = '<img src="' + path + img3 + '" alt = "">'; 
 
    var imgStr4 = '<img src="' + path + img4 + '" alt = "">'; 
 
    var imgStr5 = '<img src="' + path + img5 + '" alt = "">'; 
 
    var imgStr6 = '<img src="' + path + img6 + '" alt = "">'; 
 
    var imgStr7 = '<img src="' + path + img7 + '" alt = "">'; 
 
    var imgStr8 = '<img src="' + path + img8+ '" alt = "">'; 
 
    var imgStr9 = '<img src="' + path + img9 + '" alt = "">';

+0

你可以寫類似的功能活動和 – Yogesh

+0

你的意思是'無功ARR使用返回值= [];對於(var i = 0; i <9; i ++){ arr.push(''); }' – mplungjan

+0

只需重新排序並使用llops。這裏有一個通用的配方:假設A1是第一次動作A的迭代,你將A1,A2,A3 .. B1,B2,B3 .. C1,C2,C3...重新命名爲A1,B1,C1,A2 ,B2,C2'然後循環遍歷'(1-n){Ax,Bx,Cx}'。 – Bellian

回答

3

使用函數和數組:

function randIndex(){ 
    return Math.floor(Math.random() * imgAr.length); 
} 

const nums = Array.from({length:9}, randIndex); 

function getImage(index){ 
return '<img src="' + path + imgAr[index] + '" alt = "">'; 
} 

const imgs = nums.map(getImage); 
1

您可以使用簡單的循環和數組。但不是九個變你九長數組的結果:

var imgStr = []; 

for (i = 1; i <= 9; i++) { 
    var num = Math.floor(Math.random() * imgAr.length); 

    imgStr[i] = '<img src="' + path + imgAr[num] + '" alt = "">'; 
} 
相關問題