2017-04-08 25 views
0
user_input = ""; 
answer = ""; 

Array.greeting = ["hi", "hello"] 
Array.names = ["john","james"] 

user_input = document.getElementById('user_input').value.toLowerCase(); 
document.getElementById('text_input').innerHTML = user_input; 

documnet.getElementById('say_something').innerHTML = say; 
if(""){} 
else{} 
if(Array.greeting.includes(user_input) > 0){ 
    say = "Hello"; 
} 
if(Array.names.includes(user_input) > 0){ 
    say = "User"; 
} 

這就是我理解和啓動並運行正確的輸出,但我怎麼可以使用輸入「喂約翰」,並獲得「你好用戶」的輸出與烤出來的數組?如何檢查字符串的一部分是否在數組中?

+0

'documnet'是一個錯字。當該線路運行時'say'沒有被定義。 – Xufox

+1

你意識到你正在向'Array'對象添加屬性,而不是聲明變量?假設你知道這一點,你爲什麼要採取這種方法? –

+0

這實際上並不是代碼的一部分,而是匆忙做出來的。 'if(Array.greeting.includes(user_input)> 0){if} =「Hello」; (Array.names.includes(user_input)> 0){ } if =「User」; }' 我需要將這兩個結合起來,以便答案既可以來自兩者,也可以來自組合目標。 –

回答

0

你可以做這樣的:

var greetings = ["hi", "hello"]; 
 
var names = ["john","james"]; 
 

 
submit.onclick = function() { 
 
    // Split input into words, and convert that array to a Set for fast lookup 
 
    var words = new Set(user_input.value.split(/\s+/)); 
 
    // Choose a greeting that is not among the input words. 
 
    // If all of them occur in the input, take the first greeting word 
 
    var greeting = greetings.find(greeting => !words.has(greeting)) || greetings[0]; 
 
    // Choose a name that is not among the input words (or take the first) 
 
    var name = names.find(name => !words.has(name)) || names[0]; 
 
    // Output with textContent (not innerHTML!) 
 
    text_input.textContent = user_input.value; 
 
    say_something.textContent = greeting + ' ' + name; 
 
}
Input: <input id="user_input"><button id="submit">Submit</button><br> 
 

 
You said: <span id="text_input"></span><br> 
 
Reply: <span id="say_something"></span>

顯然,當你進入這兩個「喜」和「你好」,代碼將無法找到問候使用。在這種情況下,它使用數組中的第一個問候語(「hi」)。同樣的原則適用於名稱。

+0

不是我期望的,而是一個巨大的謝謝!這有助於我的發展。願武力與你同在:D –

0

讓我們將您的要求簡化爲: 您想檢查數組「arr」中的任何元素是否包含字符串「s」的一部分。

var check = function(arr, s) { 
    for (var i = 0; i < arr.length; i++) { 
    if (s.indexOf(arr[i]) > -1) { 
     return true; 
    } 
    } 
    return false; 
} 
+0

'Array.Greeting = [「hi」,「hello」]; Array.Names = [「john」,「james」]; (Array.Greeting.includes(user_input)> 0){ say =「Hello。」; (Array.Names.includes(user_input)> 0){ } if =「User」; }' 這對我也一樣,但我怎麼檢查'user_input'是否有來自兩個數組的值?例如「hi john」。 –

+0

擴展我的解決方案,'if(check(Array.greeting,user_input)&& check(Array.names,user_input)){say =「Hello User」}' – lazyvab

相關問題