简体   繁体   中英

JavaScript - include() - A check to see if multiple elements are in an array

hope you can help. I've got an empty array in my project which fill up as certain buttons are pressed (using push()). I want to know when a certain set of elements are in the array.

In the below code, it seems to work, the 3 elements are all in the array so it prints 'yes'. If I take out the last element ("TR"), it prints 'nope'. However, if I take out either of the first 2 elements, it prints 'yes'. It seems to be only focusing on the last element in the includes() function.

Is there any way to have the include() or something similar, check to see if all elements are in my array? Keep in mind that the array could have many more elements and they won't be sorted.

Thanks in advance.

var arr = ["TL", "TM", "TR"];

if (arr.includes("TL" && "TM" && "TR")){
    console.log("yes");
} else {
    console.log("nope");
}

The issue is in your if statement because includes() returns a boolean based on the string parameter. A better way of doing this would be to use something like:

if(arr.includes("TL") && arr.includes("TM") && arr.includes("TR")) {
  console.log("yes");
}

If you have lots of elements in your array I would suggest something more along the lines of:

var flag = true;
for(i=0; i<arr.length; i++) {
  if(!arr.includes(arr[i])) {
    flag = false;
  }
}
if(flag) {
  console.log("yes");
}

This can be done cleanly using the reduce method of arrays. Here's how to do it with your example:

var arr = ["TL", "TM", "TR"];
var fails = ["TL"] // This will return false
var succeeds = ["TL", "TM", "TR"] // This will return true
var includesAll = (array_to_check) => arr.reduce(
    (accumulator, current) => accumulator && array_to_check.includes(current),
    true
)

if (includesAll(succeeds)){
    console.log("yes");
} else {
    console.log("nope");
}

Even though the above answers show methods to get your desired result, I'm surprised no one has addressed why your original attempt didn't work. This gets into some foundational rules that JavaScript follows: how functions are called, logical operator evaluation, and operator precedence.

Calling arr.includes()

First off, you have a function includes which takes a single string argument. You have given this argument an expression instead of a string, so it is going to evaluate the expression. If the evaluation produces a string, it will return that value. If it produces a different type, it will attempt to convert the result to a string. So to clear it up, you haven't given it 3 strings to look for, but one expression that will be evaluated and become the string you are looking for.

Logical Operator Evaluation

But what is the value of that string? In JavaScript, the logical operators work in a way that can shortcut and return one of the values being evaluated. In most cases, we'd be comparing boolean values, and get true or false from the evaluation, but we're working with strings here, not booleans. Strings in JavaScript can be evaluated as "truthy" or "falsy", the former being any string that has length and the latter being a string with no length (an empty string). With this in mind, the shortcut functionality of the logical AND && operator will look at the first value in the expression, and if that value is "falsy" it will return that value. If that value is "truthy" it will look at the other side of the expression and return its value.

MDN describes this logic pretty well. Given expr1 && expr2 here's the logic:

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

Order Precendence

Finally, a note on order precedence. Logical AND && is of equal precendence to itself, so your expression will read from left-to-right. If, say, your expression was "TL" || "TM" && "TR" "TL" || "TM" && "TR" the "TM" && "TR" expression would be evaluated first since logical AND && has a higher precendence than logical OR || .

Evaluating Your Expression

Knowing all of this, we can pick apart what your expression is doing:

"TL" && "TM" && "TR" is comprised of all logical AND operators, so we will read this from left-to-right, starting with "TL" && "TM" . Since "TL" is a truthy string, the other side of the expression is returned which is "TM". The next expression is then "TM" && "TR" , of which "TM" is a truthy value, so "TR" is returned. In the end, the includes function is checking if the value of "TR" exists in the array, and ultimately returns true.

Again, do mark one of the others as answers here. Looping through the values you want to search for in the array is what you're looking for, and writing your own loop or using reduce accomplishes that, but I wanted to explain why your initial attempt probably seemed odd and clear up just what was happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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