2017-09-13 46 views
0

我想通過一個函數來發現兩個其他單詞之間的單詞的對象。如何通過函數參數傳遞對象?

我試圖通過:

  • sentences.para1.cat - - findStringBetween(參數1, - , - )
  • sentences.para2 - - findStringBetween( - ,parameter2, - )
  • sentences.para3 - to - findStringBetween( - , - ,參數3

控制檯應登錄:

  • 愛所有的
  • 從未有過的

sentences = { 
 
    para1: [ 
 
    cat: [ 
 
     "I love all the cats", 
 
     "I hate cats", 
 
     "You never had a cat before" 
 
    ], 
 
    dog: [ 
 
     "We can get a dog" 
 
    ] 
 
    ], 
 
    para2: [ 
 
    "I", 
 
    "You", 
 
    "We" 
 
    ], 
 
    para2: [ 
 
    "cat", 
 
    "dog" 
 
    ] 
 
} 
 

 
function findStringBetween(str, first, last) { 
 
    var r = new RegExp(first + "(.*)" + last) 
 
    ab = str.match(r) 
 
    result = ab[1].trim() 
 
    console.log(result) 
 
} 
 

 

 
findStringBetween(parameter1, parameter2, parameter3); 
 
//parameter1 should pass all of sentences.para1.cat 
 
//parameter2 should pass all of sentences.para2 
 
//parameter3 should pass all of sentences.para3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

代碼中沒有JSON,所以有點難以回答 –

+0

使用'JSON.stringify()'b4 pass? – Se0ng11

+0

對不起,我只是改變了這個問題......我不知道編碼語言的所有術語。 –

回答

1

你findStringBetween方法接受一個字符串,你想用它來做多個字符串。你有兩種選擇:

  1. 在循環中使用你的方法調用它爲貓的每個成員。

    for(let i=0; i< cat.length(); i++) 
        Use cat[i] 
    
  2. 您可以重構您的方法來接受數組而不是字符串。在這種情況下,你應該在你的方法中使用循環。

相關問題