创建递减至0的十进制值数组

时间:2019-01-10 15:14:26

标签: javascript jquery arrays countdown

在JavaScript / jQuery中,我生成的值可以变化,但通常为0.12或0.25。

我想生成一个数组,该数组具有一定数量的值(大约10个值左右),并在数组的开头或结尾包含上述数字。我希望这些值减少到0,例如-

var值= [0、0.02、0.04、0.06、0.08、0.10、0.12]

我只是不太确定如何做到这一点。

谢谢

2 个答案:

答案 0 :(得分:0)

您可能可以使用Array.from解决此问题:

function sequence(len, max) {
    return Array.from({length: len}, (v, k) => (k * max / (len - 1)).toFixed(2));
}

console.log(sequence(7, 0.12));

答案 1 :(得分:0)

另一种方法可能是创建一个预定义长度的新数组,然后使用map()用期望值填充该数组:

/** Variant of DefaultTableCellRenderer that automatically switches
 *  to multi-line HTML when the value contains newlines. */
class MultiLineCellRenderer extends DefaultTableCellRenderer
{
  @Override public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus, int row, int column)
  { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    int height = c.getPreferredSize().height;
    if (table.getRowHeight(row) < height)
      table.setRowHeight(row, height);
    return c;
  }

  @Override protected void setValue(Object value)
  { if (value instanceof String)
    { String sVal = (String)value;
      if (sVal.indexOf('\n') >= 0 && // any newline?
        !(sVal.startsWith("<html>") && sVal.endsWith("</html>"))) // already HTML?
        value = "<html><nobr>" + htmlEncodeLines(sVal) + "</nobr></html>";
    }
    super.setValue(value);
  }

  /** Encode string as HTML. Convert newlines to &lt;br&gt; as well.
   * @param s String to encode.
   * @return Encoded string. */
  protected static String htmlEncodeLines(String s)
  { int i = indexOfAny(s, "<>&\n", 0); // find first char to encode
    if (i < 0)
      return s; // none
    StringBuffer sb = new StringBuffer(s.length() + 20);
    int j = 0;
    do
    { sb.append(s, j, i).append(htmlEncode(s.charAt(i)));
      i = indexOfAny(s, "<>&\n", j = i + 1);
    } while (i >= 0);
    sb.append(s, j, s.length());
    return sb.toString();
  }

  private static String htmlEncode(char c)
  { switch (c) {
    case '<': return "&lt;";
    case '>': return "&gt;";
    case '&': return "&amp;";
    case '\n': return "<br>";
    default: return Character.toString(c);
  } }

  private static int indexOfAny(String s, String set, int start)
  { for (int i = start; i < s.length(); ++i)
    if (set.indexOf(s.charAt(i)) >= 0)
      return i;
    return -1;
  }
}