2015-08-26 62 views
0

我有兩個數組,需要從一個數組中找到索引並獲取另一個數組索引上的元素。 出於某種原因,一切看起來不錯,但方法仍然返回undefined,但我期待Station_2作爲索引是2通過。它返回undefinedJavascript的foreach問題===不工作

function FindBestStation(x,choosenItem,y) 
    { 
     x.forEach(
     function(tempItem) 
     { 
      if(tempItem===choosenItem) 
      { 
       return y[tempItem-1]; 
      } 

     }); 
    } 
    var x=[1,2,3,4, 10]; 
    var y=['Station_1','Station_2','Station_3','Station_4','Station_10']; 
    var choosenItem=2;//another algorithm finds this value 

    var choosenElement=FindBestStation(x,choosenItem,y); 
    console.log(choosenElement); 
+0

tempItem用作forEach循環指數,這可能無法使用總是在數組變量'x' –

+0

我看到一個問題的提出但沒有真正的問題;你究竟問什麼? – Matt

回答

0

JavaScript的foreach方法沒有破壞,所以它沒有===在foreach上發出它的return語句是問題。

我已修改代碼這應該工作 Reference here

function FindBestStation(x,choosenItem,y) 
{ 
    var elementFound; 
    x.forEach(
    function(tempItem) 
    { 

     if(tempItem===choosenItem) 
     { 
      elementFound= y[tempItem-1]; 
      return; 

     } 

    }); 
    return elementFound; 
} 

var x=[1,2,3,4, 10]; 

var y=['Station_1','Station_2','Station_3','Station_4','Station_10']; 

var choosenItem=2;//another algorithm finds this value 

var choosenElement=FindBestStation(x,choosenItem,y); 
console.log(choosenElement); 
+0

正是我想要的歡呼!! :) –

1

return語句是你.forEach()回調中。因此它不會做任何有用的事情。 「FindBestStation」函數根本沒有return語句,因此它返回undefined

0

回調調用與三個參數:

元素值

元素索引

陣列正被遍歷

你可以做這樣的事情:

function FindBestStation(x,choosenItem,y) 
 
    { 
 
     x.forEach(
 
     function(tempItem,index,array) 
 
     { 
 
      if(tempItem===choosenItem) 
 
      { 
 
       choosenElement = y[index]; 
 
      } 
 

 
     }); 
 
    } 
 
    var x=[1,2,3,4, 10]; 
 
    var y=['Station_1','Station_2','Station_3','Station_4','Station_10']; 
 
    var choosenItem=2;//another algorithm finds this value 
 

 
    var choosenElement; 
 
    FindBestStation(x,choosenItem,y); 
 
    console.log(choosenElement);