简体   繁体   English

条件语句不起作用-数组

[英]Conditional statement not working - arrays

I have this (novice) JS question: 我有这个(新手)JS问题:

I have this simple function function movieStorage() , which I want to check if the Yes button is clicked - if so it should storage the output (RandomItem in a new array (movieSaver). 我有这个简单的函数函数movieStorage() ,我想检查是否单击了Yes按钮-如果这样,它应该将输出(RandomItem存储在新数组(movieSaver)中)。

the Output is a random value from the hMovies-array - generated when the Yes button is clicked. 输出是hMovies数组中的随机值-单击“是”按钮时生成。

 var hMovies = [ "hMovie1", "hMovie18" ]; var movieSaver = []; var randomItem = hMovies[Math.floor(Math.random() * hMovies.length)]; document.getElementById("buttonYes").addEventListener("click", ifClickedYes); function ifClickedYes() { document.getElementById("showResult").innerHTML = randomItem; return (true); } function movieStorage() { if (ifClickedYes()) { movieSaver.push(randomItem); } } console.log(movieSaver); 
 <button id="buttonYes">Yes</button> <div id="showResult"></div> 

There is no point to check the condition which will be always true . 没有必要检查始终为true条件。 You do not need the second function. 您不需要第二个功能。 The only thing you need is to push the elements to array in the function attached to onclick event. 您唯一需要做的就是将元素推送到onclick事件附带的函数中的数组中。

Also, use generate a new random index on click every time. 此外,每次使用时都可使用点击生成新的随机索引。

var hMovies = [
   "hMovie1",
   "hMovie18"];

var movieSaver = [];
document.getElementById("buttonYes").addEventListener("click", ifClickedYes);

function ifClickedYes(){
  var randomItem = hMovies[Math.floor(Math.random()*hMovies.length)];
  movieSaver.push(randomItem)
  document.getElementById("showResult").innerHTML = randomItem;
  console.log(movieSaver);
}

Working Snippet: 工作片段:

 var hMovies = [ "hMovie1", "hMovie18"]; var movieSaver = []; document.getElementById("buttonYes").addEventListener("click", ifClickedYes); function ifClickedYes(){ var randomItem = hMovies[Math.floor(Math.random()*hMovies.length)]; movieSaver.push(randomItem) document.getElementById("showResult").innerHTML = randomItem; console.log(movieSaver); } 
 <button id="buttonYes">Yes</button> <div id="showResult"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM