2016-09-29 54 views
-3

爲什麼數組解析不起作用?解析數組一半

var input = [ 'sam 99912222', 
 
    'tom 11122222', 
 
    'harry 12299933', 
 
    'sam', 
 
    'edward', 
 
    'harry' ]; 
 

 
var numItems = 3; 
 
console.log(input); 
 

 
var phoneNames = []; 
 
var searchNames = []; 
 
var phoneBook = []; 
 

 
for (i = 0; i < numItems; i++) { 
 
    phoneNames.push(input[i]); 
 
    var j = i + numItems; 
 
    searchNames.push(input[j]); 
 
} 
 
console.log("phoneNames: " + phoneNames); 
 
console.log("searchNames: " + searchNames);

輸出:

[ 'sam 99912222', 
    'tom 11122222', 
    'harry 12299933', 
    'sam', 
    'edward', 
    'harry' ] 
phoneNames: sam 99912222,tom 11122222,harry 12299933 
searchNames: ,, 

爲什麼searchNames未填充值?

+0

有多大你的輸入數組?索引j是否大於輸入數組的大小? – auburg

+1

如果您單擊「運行代碼段」按鈕,您將看到輸出如預期。無論您的實際輸入或您的實際代碼是別的。 – JJJ

+0

查看代碼片段,searchNames在@JJJ上填上 – havenchyk

回答

1

假設您的輸入數組看起來像下面的代碼,您的解決方案對我來說完全適用。我採用了與您在開始時添加輸入相同的代碼片段。

var input = [ 'sam 99912222', 
       'tom 11122222', 
       'harry 12299933', 
       'sam', 
       'edward', 
       'harry' 
      ]; 

這導致了以下的輸出:

phoneNames: sam 99912222,tom 11122222,harry 12299933 
searchNames: sam,edward,harry 

此外,如果你總是有這種類型的數據結構(甚至數組長度),並把你的數組長度的一半numItems ,你不應該遇到任何出界限制異常的問題。對於動態迭代值i,只取數組大小的一半:

var numItems = input.length/2; 

這裏是我完整的代碼我只是跑:

 var input = [ 'sam 99912222', 
      'tom 11122222', 
      'harry 12299933', 
      'sam', 
      'edward', 
      'harry' 
     ];   

     var numItems = input.length/2; 

     console.log(input); 

     var phoneNames = []; 
     var searchNames = []; 
     var phoneBook = []; 

     for (i = 0; i < numItems; i++) { 
      phoneNames.push(input[i]); 
      var j = i + numItems; 
      searchNames.push(input[j]); 
     } 
     console.log("phoneNames: " + phoneNames); 
     console.log("searchNames: " + searchNames); 
-1

var input = [ 'sam 99912222', 
 
    'tom 11122222', 
 
    'harry 12299933', 
 
    'sam', 
 
    'edward', 
 
    'harry' ]; 
 

 
var numItems = 6; 
 

 
var phoneNames = []; 
 
var searchNames = []; 
 
var phoneBook = []; 
 

 
for (i = 0; i < numItems; i++) { 
 
    var val = input[i].split(" "); 
 
    phoneNames.push(val[0]); 
 
    searchNames.push(val[1]); 
 
} 
 
console.log("phoneNames: ", phoneNames); 
 
console.log("searchNames: ", searchNames);

+0

結果將爲 phoneNames:sam,tom,harry,sam,edward,harry searchNames:99912222,11122222,12299933 ,,, –