簡體   English   中英

如何在if else語句中檢查數組是否包含某個值

[英]How to check within an if else statement if an array contains a certain value

求助於第一個stackover流程帖子!

我試圖根據單擊的“字符”按鈕來更改結果。

因此,我從一個名為gendr = [];的變量開始gendr = [];

如果單擊名為“ marge”的按鈕,則margeFunction將運行,這會將值“ female”推入數組內部。 如果單擊“ Henry”按鈕,將運行henryFunction,它將值“ male”壓入數組。

更高版本的函數包含if else語句,如果該數組包含值,則為male“出現男句”。 否則,如果數組值是女性,則顯示“女性句子”。

 function helloFunction() {
   if(gendr[female]) {
       document.getElementById ('traitText').innerHTML = "and says the word hello in every sentence she speaks";
   } else {
      document.getElementById ('traitText').innerHTML = "and says the world hello in every sentence he speaks"
   }
 }

我不太確定該怎么做,我只是猜測了一下,但是我想知道正確的方法! 提前致謝 :)

gendr[female]不起作用,因為沒有female變量,並且您不想訪問數組中的female位置,相反,聽起來好像您想要獲取該數組的最后一個值。 可以使用gendr[gendr.length - 1]來完成。 現在,您要檢查該值是否為"female"並且可以通過比較( === )進行檢查。

但是,如果根本不需要數組,那是有問題的,為什么不只保留一個布爾值( isFemale = false; )?

有多種方法可以實現您想要實現的目標。 indexOf方法是檢查數組中是否存在元素的有效方法。 此外,ECMAScript 2016具有一種新方法, includes檢查數組中是否存在元素。 這是一個例子:

var gender = ['male', 'female'];

function checkInArray(genderArray) {
  if(genderArray.indexOf('male') > -1) {

    //do something
    return 'male found';
  } else {
    //do something
    return 'female found';
  }
}

function checkInArray2(genderArray) {
  return genderArray.includes('male'); 
}

console.log(checkInArray2(gender))

var array = [1,2,3,4,5];
array.includes(2);     //true
array.includes(4);     //true
array.includes(1, 2);  //false (second parameter is the index position in this array at which to begin searching)

檢查一下: https : //playcode.io/373046

您問題的HTML部分應如下所示

<button onclick="helloFunction('female')">Marge</button>
<button onclick="helloFunction('male')">Henry</button>

然后的JavaScript

function helloFunction(gendr) {
  if(gendr=="female") ...
}

我相信您的問題更多是關於參數傳遞,而不是數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM