试图更好地降低我的代码密度,但我被这个问题难住了。当数组嵌套在对象内时,使用下拉菜单在选项 1-24 之间进行选择的最佳方法是什么?
我正在尝试制作一个 Chrome 扩展程序,为本地时间的不同时间函数(即 1 小时、3 小时、12 小时等)创建通知
我知道它可以与这里的数组一起使用:
var d = new Dropdown({
id: 'd',
val: 'custom:',
data: ['1 hour', '2 hours', '3 hours', '4 hours', '5 hours', '6 hours', '7 hours', '8 hours', '9 hours', '10 hours', '11 hours', '12 hours', '13 hours', '14 hours', '15 hours', '16 hours', '17 hours', '18 hours', '19 hours', '20 hours', '21 hours', '22 hours', '23 hours', '24 hours'],
cb: function cb(newval) {
alert(newval);
}
});
对于 future ,为了避免重写 24 个单独的选项,这个逻辑是否有效?它将项目作为字符串数组返回,并将更新的值作为第一个参数,但我不确定这是否是不好的做法。
let h = Array.from(Array(24).toString(),
(_hour, index) => `${[index + 2]} hours`).map(String);
const itr = h.values();
console.log(Array.isArray(h)); // outputs true
console.log(itr); // outputs {[Iterator]}
// here's where I get lost
如果我缺少更简单的方法,请告诉我。与 html 输入相比,我更喜欢这个,因为我不会弄乱计时器中的日期,只是记录本地时间 +n。
最佳答案
使用map
并检查是否使用复数。
const hours = new Array(24).fill(0).map((_, i) => `${i+1} hour${i > 0 ? 's' : ''}`)
console.log(hours)
关于javascript - 使用 Array.from( Array(n) ).map(String) 的 24 小时下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60615791/