2015-10-04 33 views
0

循環我有2個陣列對於2個解析陣列

var a = [ 
    "4", 
    "@", 
    "/\\", 
    "/-\\", 
    "^", 
    "∂", 
    "λ", 
    "α", 
    "(!", 
    "Z", 
    "α" 
]; 
var r = [ 
    "1²", 
    "2", 
    "?", 
    "P\\", 
    "[\"/_", 
    "l\"/_", 
    "|-", 
    "|2", 
    "|?", 
    "®", 
    "12", 
    "/2", 
    "I2", 
    "|^", 
    "|~", 
    "(r)", 
    "|`", 
    "l2", 
    "Я", 
    "ʁ", 
    "я" 
]; 

我需要收杆到1聲明兩個陣列

以下是我有:

for (var index_a=0, index_r=0; index_a < a.length, index_r < r.length ; ++index_a, ++index_r) { 
    new_a = a[index_a]; 
    console.log(new_a); 
    new_r = r[index_r]; 
    console.log(new_r); 
}; 

輸出:

the element from A array: 4 
the element from R array: 1² 
the element from A array: @ 
the element from R array: 2 
the element from A array: /\ 
the element from R array: ? 
the element from A array: /-\ 
the element from R array: P\ 
the element from A array:^
the element from R array: ["/_ 
the element from A array: ∂ 
the element from R array: l"/_ 
the element from A array: λ 
the element from R array: |- 
the element from A array: α 
the element from R array: |2 
the element from A array: (! 
the element from R array: |? 
the element from A array: Z 
the element from R array: ® 
the element from A array: α 
the element from R array: 12 
the element from A array: undefined 
the element from R array: /2 
the element from A array: undefined 
the element from R array: I2 
the element from A array: undefined 
the element from R array: |^ 
the element from A array: undefined 
the element from R array: |~ 
the element from A array: undefined 
the element from R array: (r) 
the element from A array: undefined 
the element from R array: |` 
the element from A array: undefined 
the element from R array: l2 
the element from A array: undefined 
the element from R array: Я 
the element from A array: undefined 
the element from R array: ʁ 
the element from A array: undefined 
the element from R array: я 

問題是一個數組更長然後是另一個,並且在完成解析最短的一個之後,它繼續最長的一個,但是最短的那個值是未定義的。當最短的數組結束時,我需要保存最後一個值。我怎樣才能做到這一點。 謝謝。

+0

你只需要最後一個元素? – baao

+0

當第一個數組結束時不清楚你想要做什麼 - 停止對第二個數組的循環或僅繼續循環? –

+0

爲什麼不合並數組並迭代所有項目? – Alex

回答

0

我敢肯定,但不能對如何做到這一點1001分其實挺有意思的答案,但鑑於你的設置,你已經如上圖所示,最快捷的方法就是簡單地包圍:

if(index_a < a.length){ 
    new_a = a[index_a]; 
    console.log(new_a); 
} 

現在,如果你有5個陣列需要做到這一點,將不得不用暴力強迫每個陣列。一個更有趣的方法是從另一個返回數組第n個元素的方法開始思考(如果它存在的話),如果沒有則返回任何東西。這樣你可以忽略返回值,如果它不存在的話,就使用它。

如果所有有問題的數組都沒有返回,那麼就完成了。

有一點簡單,因爲會有一些邊緣情況需要考慮,但這可能是一個很好的方式,可以幫助我們更好地瞭解這些邊緣情況,甚至是異常拋出和捕獲。

很多簡單的方法來完成這件事。

0

檢查您試圖從短陣列中引用的值。如果未定義,則從短陣列中的最後一項獲取值。這個?:操作符可以檢查這個:

類似這樣的: new_a = a [index_a] =='undefined'?a [a.length-1]:a [index_a];