vendredi 15 octobre 2021

How do I look at an array for two specific neighboring (consecutive) elements?

Hello Everyone,

I am looking array and trying to determine if it contains at least 2 elements AND contains the elements ["*", "/"]. (Specifically in that order.)

array = ['*', '/']   <--- accept
array = ['/', '*']   <--- reject
array = ['*', '/', '%']   <--- accept
array = ['*', '/', '%', '!', '+', '-']   <--- reject
Looking for: '*', '/' 

Is my approach using if statements wrong?

In my attempt below I am using the fn checkArray to check:

  1. If the length of array is greater than or equal to 2 AND contains "*", "/"

AND

  1. If the first element in array is "*"

If both of the above are true I log to console: "FOUND IT! --> '*', '/'" and array[0), else I log "Did something else."

function checkArray (array) {
if (((array.length >= 2) && (array.includes("*" && "/"))) && (array[0] === "*")) {
    console.log("FOUND IT! --> '*', '/'")
    console.log(array[0])
} else
    console.log("Did something else.")
}

Currently my code does not have a different outcome if I change the array contents from '*', '/' or '/', '*'

Expected outcomes:

PS.. Would this be better handled using a switch statement? I do expect additional criteria to be added, such as looking for '+', '+', '-' for example.

Aucun commentaire:

Enregistrer un commentaire