简体   繁体   中英

Compare a string against a list of newly created booleans without looping,

I have created a list of new booleans in javascript, belonging to boolean values in different languages (true, false, verdadero, falso, ratt, fel, etc...)

I have done so with:

var false_swedish = new Boolean("fel");

and so on with many others.

I am trying to code a small text game as a kind of puzzle to learn (I am very beginner), so I am stuck here. Now my goal is: Since I have a list of 10 new booleans, how can I compare them against a string (what the user writes using a prompt )?

I was thinking first about creating an array with all the new words and then compare them with the string, but that defeats the point of declaring them as new Booleans and finding out if the user input is boolean, and here I am not very interested in the final result but more in the process of doing it (as I said, is just an exercise to learn)

I got as far as creating a function that checks if a variable is a Boolean, basically using:

if (value.constructor == Boolean ){
    return true;

and then using that function to add a new method to String with prototype , so I can check against the string provided by prompt . But of course, that function is useless, because it's assuming that the variables might be booleans, and they are not. They are always strings...

Am I trying to complicate it too much?

Thanks for any ideas

Yes, you are trying to complicate it too much.

new Boolean("any string") is useless, since with any non-empty string the resulting variable would be true. If your goal was to check whether the user entered 'true or 'false' only, the best solution would be to compare his input to 'true' . But in case there are lots of possible inputs, you can use an object:

// this object contains every string value you want to include in your script defined by a number
var predefinedValues = {'true': 1, 'false': 0, 'verdadero':1, 'falso':0};
// i assume userInput contains user input
if(predefinedValues[userInput] == 1) {
    //true
}
else {
    //false or not found in array
}

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