简体   繁体   English

如何显示索引数组的特殊词?

[英]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:当用户想要找出日期时间时,我想在 < div > 中显示特定的单词,例如:

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?如果我的数组的长度,将来会有 999 个索引吗? To fill each index, I'll spend many time, is it possible somehow add ( if, else if ) into array?为了填充每个索引,我会花很多时间,是否有可能以某种方式将( if,else if )添加到数组中?

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:就像问题中的 24 示例一样,它可以创建如下:

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.然后使用 function,您可以检查您的小时值是否在任何范围内。 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.将来,您只需将新范围添加到您的 rangeArray 中,代码仍然可以正常工作。

You can maintain array of arrays and each sub array is window of "last index" and "type of item".您可以维护 arrays 数组,每个子数组是“最后一个索引”和“项目类型”的 window。

In the following same在以下同
0-6 --> work 0-6 --> 工作
7-7 --> fun 7-7 --> 有趣
8-23 --> movie 8-23 --> 电影

 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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