javascript - 我怎样才能缩短这个?
问题描述
我正在寻找缩短我目前正在从事的项目的硬编写代码。问题是我不知道该怎么做,因为我还很新。
我已经硬编码,用谷歌搜索我还能做什么,但没有任何帮助。
if (spins >= 3 && spins <= 5) {
textSize(40);
text("H", 20, 40);
} if (spins >= 6 && spins <= 8) {
textSize(40);
text("HA", 20, 40);
} if (spins >= 9 && spins <= 11) {
textSize(40);
text("HAP", 20, 40);
} if (spins >= 12 && spins <= 14) {
textSize(40);
text("HAPP", 20, 40);
} if (spins >= 15 && spins <= 17) {
textSize(40);
text("HAPPY", 20, 40);
}
没有任何问题我只是想缩短它,它按原样完美运行,但我仍在努力学习,而且我领先于全班,但我无法从谷歌或我的同龄人那里找到帮助。
解决方案
请注意,文本字符串长度直接对应于Math.floor(spins / 3)
- 使用它来确定要传递给的字符串的长度text
:
const strLen = Math.floor(spins / 3);
textSize(40);
text('HAPPY'.slice(0, strLen), 20, 40);
const getText = (spins) => {
const strLen = Math.floor(spins / 3);
console.log('HAPPY'.slice(0, strLen));
};
getText(3);
getText(4);
getText(5);
getText(6);
getText(14);
getText(15);
推荐阅读
- rust - 如何在 Rust 中为结构实现 Rng 和 RngCore?
- python - 是否可以矢量化 scipy.optimize.fminbound?
- ros - ROS:tf 与 RPlidar
- laravel - Nginx 配置以允许应用程序中的自定义域
- php - zsh:找不到命令:php
- python - Pandas 根据条件填充 NaN
- python - python:json属性数(嵌套)
- c# - 是否可以在 Web 应用上使用 Azure 认知服务?
- c# - 禁用高 DPI 缩放
- python - 无法将函数调用到其他函数中,它在我调用的计算器(选择)处的 cal 函数中出现错误