Javascript基本循环帮助-基本

Javascript基本循环帮助-基本,javascript,Javascript,我现在正在学习Javascript,我有一个问题一直困扰着我 因此,我在这里需要做的就是在这个输入框中键入一种颜色,单击按钮,并将标题更改为键入的颜色,前提是键入的颜色位于变量中指定的数组中 我的代码有一半正常工作。。。它会检查数组中是否有键入的任何颜色,但每次都会弹出警报按钮,是否有方法仅在键入的颜色不在数组中时才弹出警报 工作代码: Javascript代码: const myHeading = document.getElementById('myHeading'); const myBu

我现在正在学习Javascript,我有一个问题一直困扰着我

因此,我在这里需要做的就是在这个输入框中键入一种颜色,单击按钮,并将标题更改为键入的颜色,前提是键入的颜色位于变量中指定的数组中

我的代码有一半正常工作。。。它会检查数组中是否有键入的任何颜色,但每次都会弹出警报按钮,是否有方法仅在键入的颜色不在数组中时才弹出警报

工作代码:

Javascript代码:

const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
const myTextInput = document.getElementById('myTextInput');

var colors = ["red", "black", "blue"];

myButton.addEventListener('click', () => {
    for (var i=0; i<colors.length; i++){
        if (myTextInput.value === colors[i]){
            myHeading.style.color = myTextInput.value
        } else {
            alert("no color")
        }
    }

});
const myHeading=document.getElementById('myHeading');
const myButton=document.getElementById('myButton');
常量myTextInput=document.getElementById('myTextInput');
变量颜色=[“红色”、“黑色”、“蓝色”];
myButton.addEventListener('单击',()=>{

对于(var i=0;i不要在循环内执行此操作。在找到匹配项时使用变量来标记,然后在循环后检查该标记并相应地显示警报。尝试以下操作:

myButton.addEventListener('click', () => {
  var found = false;
  for (var i = 0; i < colors.length; i++) {
    if (myTextInput.value === colors[i]) {
      myHeading.style.color = myTextInput.value
      found = true;
    }
  }
  if (!found)
    alert("no color");
});
myButton.addEventListener('click', () => {
  if (colors.indexOf(myTextInput.value) > -1)
    myHeading.style.color = myTextInput.value
  else
    alert("no color");
});

不要在循环内执行此操作。在找到匹配项时使用变量来标记,然后在循环后检查该标记并相应地显示警报。请尝试以下操作:

myButton.addEventListener('click', () => {
  var found = false;
  for (var i = 0; i < colors.length; i++) {
    if (myTextInput.value === colors[i]) {
      myHeading.style.color = myTextInput.value
      found = true;
    }
  }
  if (!found)
    alert("no color");
});
myButton.addEventListener('click', () => {
  if (colors.indexOf(myTextInput.value) > -1)
    myHeading.style.color = myTextInput.value
  else
    alert("no color");
});

使用布尔变量,如果找到匹配的颜色,则将其设置为true。在for循环的末尾检查布尔值是否为true。如果为false(初始值),则alert()才考虑使用哈希(对象)而不是颜色数组。这样,您就不必搜索整个数组。如果找到匹配的颜色,请使用布尔变量并将其设置为true。在for循环的末尾检查布尔值是否为true。如果为false(初始值),则alert()才考虑使用哈希(对象)而不是一个数组的颜色。这样你就不必搜索整个数组。