I want to assign multiple strings to one variable, but I get an error. - - JavaScript

Asked 2 years ago, Updated 2 years ago, 101 views

    const arr = ['a', 'b', 'c', 'd', 'e'];
    var x = "b" || "d" || "g" || "h" || "z";
    const the_number_of_x = arr.filter(i => i === x).length;
    if (the_number_of_x === 2) {
        console.log("success!")
    } } else {
        console.log("fail!")
    }

x has "b" and "d" in the variable x, and 'b' and d' have a total of two, so isn't the_number_of_x> a code? But I don't know why "fail!" comes out instead of "success!".

I'd appreciate it if you let me know.

javascript or string array filter

2022-09-20 17:55

1 Answers

1. If you try console.log(x), x is always "b".

In JavaScript, A || B means A or B if "A" is acceptable.
So "b" || "d" || "g" || "h" || "z" is always "b".
Regardless of how many || operations are defined in the back, "b" is a useful material.

2. The fact that multiple strings are specified in a single variable is arr.

How do you put multiple strings in a variable? There are two main ways. You can put multiple strings in an iterable or enumerable data type that contains multiple data, or you can write a single string that connects multiple strings with a specific delimiter.

The first way is arr, and the second way is, say, this way.

let x = "b|d|g|h|z";
let y = x.split('|'); // eventually y is array → itterable

3. So what do you want to do? arrr You can make another one and compare it.

arrr is already a variable that 'specified' multiple strings. You can make another similar one and then compare the two.

// To summarize, it is to find the intersection. Copied here: https://stackoverflow.com/a/1885569
const arr = ['a', 'b', 'c', 'd', 'e'];
let x = ["b", "d", "g", "h", "z"];
let arr_and_x = arr.filter(function (n) {
    return x.indexOf(n) !== -1;
});
console.log(arr_and_x.length == 2 ? 'success!' : 'failed!');


2022-09-20 17:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.