首页 > 解决方案 > 我怎样才能缩短这个?

问题描述

我正在寻找缩短我目前正在从事的项目的硬编写代码。问题是我不知道该怎么做,因为我还很新。

我已经硬编码,用谷歌搜索我还能做什么,但没有任何帮助。

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

没有任何问题我只是想缩短它,它按原样完美运行,但我仍在努力学习,而且我领先于全班,但我无法从谷歌或我的同龄人那里找到帮助。

标签: javascript

解决方案


请注意,文本字符串长度直接对应于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);


推荐阅读