为什么第二个if语句在我的代码中不起作用?

时间:2019-06-19 20:53:19

标签: javascript html if-statement const

我目前正在研究一个项目,如果您单击按钮并说出计算机会响应的内容。我已经建立了一个名为“问候”的常量,并在其中放置了一些我放入的字符串。然后,我在readOutLoud函数中放置一个if语句。在if语句中,计算机检查用户是否输入了任何关键字(现在它只能响应您的情况),然后使用Math。随机下限,我也插入了if语句,以选择我在问候语const中输入的3个选项之一。因此,如果您现在按下通话按钮并说出您的状况,它将以我在问候常量中输入的3个选项之一做出响应。由于某种原因,我放在第一条下面的第二条if语句不起作用,为什么会这样呢?第二个唯一的不同是它使用了不同的关键字并获得了另一个const。

const btn = document.querySelector('.talk');
const content = document.querySelector('.content');
const greetings = [
				'If you are good im good to ?', 
				'Im doin alright', 
				'Im tired ?'
];
const weather = [
				'Ask the weatherman!', 
				'okay I guess' 
				
];
const name = [
	'My name is techwali', 
	'techwali!'
];
const hello = [
	'Why hello! How are you doing today?', 
	'Hey there How are you?'
]
const hru = [
	'thats great!', 
	'Im so sorry to hear that', 
	'Feel better soon!'
]
const SpeechRecognition = 
	window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();

recognition.onstart = function() {
	console.log('voice is activated speak into the mic');
};
recognition.onresult = function(event) {
	const current = event.resultIndex;
	
	const transcript = event.results[current][0].transcript;
	content.textContent = transcript;
	readOutLoud(transcript);
}

btn.addEventListener('click', () => {
	recognition.start();
});

function readOutLoud(message) {
	
	const speech = new SpeechSynthesisUtterance();
	speech.text = 'I dont know what you said';
	if(message.includes('how are you')) {
		 const finalText = 
		 greetings[Math.floor(Math.random() * greetings.length)];
		 speech.text = finalText;
		
	} 
	if(message.includes('hey', 'hi', 'hello')) {
		 const finalText = 
		 hello[Math.floor(Math.random() * hello.length)];
		 speech.text = finalText;
		
	} 

	
	speech.volume = 1;
	speech.rate = 1;
	speech.pitch = 1;
	window.speechSynthesis.speak(speech);
		
	} 
	
<!DOCTYPE html>
<html>
<head>
	<title>Page Title</title>
</head>
<body>
<button class="talk">Talk</button>
<h3 class="content"></h3>


</body>

1 个答案:

答案 0 :(得分:1)

您的代码不起作用,因为“ includes”方法检查数组是否包含某个值,而不是多个值之一。您可以使用“ some”方法来完成这项工作。

if(['hey', 'hi', 'hello'].some(word => message.includes(word))) {
    const finalText = hello[Math.floor(Math.random() * hello.length)];
    speech.text = finalText;
}

这将遍历数组,检查消息是否包含任何指定值。