简体   繁体   中英

Is there an elegant way to handle potential array element comparison to object value?

I have a game in which contestants are presented two pictures at random. The pictures may be red or blue and the goal is to select any red pictures and submit their vote. When their vote is cast, they should be awarded a point for any red pictures they selected and a point for any blue pictures they did not select.

Each image has an attribute for the filename and the color, like so:

<div id="box1" class="selectItem" data-filename="image1.png" data-color="red">

When a contestant selects one or more images, the filename and color are pushed into an array kept in a hidden form that may look like so:

[image1.png, red] but could also look like so: [image1.png, red, image2.png, blue] or could also be empty.

I have an object that holds information about the images currently being displayed. It's built like so:

const image1 = $('box1').attr('data-filename');
const color1 = $('box1').attr('data-color');
const image2 = $('box2').attr('data-filename');
const color2 = $('box2').attr('data-color');
const obj = {};
obj[image1] = color1;
obj[image2] = color2;

So, the object could look like so:

{
  ['image1.png']: 'red',
  ['image2.png']: 'blue'
}

All awarded points are then and added to a score kept in sessionStorage.

What's the most elegant way to compare the user's selection (array) against the displayed images (object) to:

  1. Award a point for any red images selected
  2. Award a point for any blue images NOT selected

I just wound up doing this:

for (let [key, value] of Object.entries(obj)) { 
    if (key === array[0]) {
        if (value === 'red') {
            // update my score
        }
    } else if (key !== array[0]) {
        if (value === 'blue') {
            // update my score
        }
    }
}

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