简体   繁体   中英

How can I display special word for index array?

I still newbie and faced with one challenge.

I want to display specific word in < div > when user wants to find out the datetime for example:

let today = new Date;

let time = today.getHours()
let hours= [
    'work',
    'work',
    'work',
    'work',
    'work',
    'work',
    'work',
    'fun',
    'work',
    'work',
    'work',
    'work',
    'work',
    'work',
    'work',
    'fun',
    'fun',
    'fun',
    'work',
    'work',
    'fun',
    'fun',
    'fun',
    'fun',
  ]
let hoursName = hours[today.getHours()];
console.log(hoursName);

My code works, but it a little bit not properly I think. If length of my array, in future, will 999 indexes? To fill each index, I'll spend many time, is it possible somehow add ( if, else if ) into array?

You can create an array which contains the start and end index for "fun" values. Like for the 24 example in the question, It can be created as below:

var funRanges = [[7, 7], [15, 17], [21, 23]]; // [[Start, end]] (Both inclusive)

Then using a function, you can check if your hour value lies in any of the ranges. Like below:

 var funRanges = [[7, 7], [15, 17], [21, 23]]; // [[Start, end]] (Both inclusive) var getHourName = (hour) => funRanges.some(x => hour >= x[0] && hour <= x[1])? 'fun': 'work'; console.log(getHourName(1)) // work

在此处输入图像描述

In future, You can just add new ranges into your rangeArray, and the code will still work fine.

You can maintain array of arrays and each sub array is window of "last index" and "type of item".

In the following same
0-6 --> work
7-7 --> fun
8-23 --> movie

 const get = (index) => { // array of array, each array is "last index" and "type" const hours = [ [6, "work"], [7, "fun"], [23, "movie"], ]; const slot = hours.find((arr) => arr[0] >= index); return slot[1]; }; console.log(get(5)); console.log(get(7)); console.log(get(15));

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