2012-03-05 72 views
0

我試圖在JavaScript中將整數字符串拆分成一個數組。將整數字符串拆分爲數組 - 元素不被識別

我原本:

m.rows[7] = new Array (8,11); 

而且我將其更改爲:

var nearby = nearby.split(","); 
m.rows[7] = new Array (nearby); 

(並設置有一個逗號在我的關卡編輯器分離合適的整數變量當我打印當我打印「附近的[1]」到控制檯時,我得到11)

但是,我有這個代碼,我試圖匹配其中一個th中的元素È陣列與另一個數組中的元素:

for (var i = m.rows[id].length-1; i >= 0; i--) { 
     // If the loop finds an element ID that matches the ID of the last element in the path array, do this: 
     console.log('test nearby 2: ' + m.rows[id][i]); 
     if (m.rows[id][i] == this.path_array[this.path_array.length-1].id) { 
      // Loop through the one array 
      for (var j = all_nodes.length-1; j >= 0; j--){ 
       // If the ID of one of one of these entities matches the id of the instance that was just clicked 
       if (all_nodes[j].id == id) { 

        // Activate that node: 
        all_nodes[j].active = true; 
       } 
      } 
      break; 
     } 

當我居然把「8,11」到上述手動上述工程完美陣列。但是,當我嘗試使用「分離」到數組中的「附近」時,它不會。並在上面的「測試附近2」打印到控制檯,當我使用「附近」時,「8,11」被打印。當我手動輸入「8,11」時,我得到「11」。

我相當新的JavaScript,所以我可能會錯過這裏非常明顯的東西 - 任何人都可以擺脫一些光?

謝謝!

+0

目前還不清楚「附近」究竟是什麼;它是一個逗號分隔值的字符串?如果是這樣,請注意分割它將導致字符串,而不是實際的「數字」。這*可能會沒問題,因爲JS會進行類型轉換,但它取決於操作的順序。更容易/更安全,只需在分割後讓他們編號。 – 2012-03-05 18:54:58

+0

Dave,Nearby是一個用逗號分隔的字符串,如你所建議的。 Minitech的回答下面最終幫助我做我正在嘗試:) – spectralbat 2012-03-05 19:23:27

回答

1

這不是陣列如何工作。在new Array(8, 11),811參數。在new Array(nearby),nearby一個參數。然而,要實現你所需要的功能,這很簡單; nearby已經是一個數組,所以只需給它分配:

m.rows[7] = nearby; 

或者,如果類型困擾你:

m.rows[7] = [parseInt(nearby[0], 10), parseInt(nearby[1], 10)]; 

請注意,這裏我使用數組文本語法,[][a, b]基本上等同於new Array(a, b),您應該在可能的情況下出於各種原因使用字面語法。

+0

謝謝!這工作完美。 – spectralbat 2012-03-05 19:17:21

1

nearby已經是一個數組。沒有理由撥打new Array(anArray)。事實上,你不應該認爲這不會是你想象的那樣。

編輯:

這是一個演示問題的小提琴。注意數組中的第一個元素實際上是一個包含兩個元素的數組,而不僅僅是第一個元素。

http://jsfiddle.net/V7QLN/