如何将两个数从负数填充到正数?

时间:2018-11-30 19:18:51

标签: javascript

如何从负数到正数填充数组,如:

  

数字['-3','-2.5','-2','1.5','1','0.5','0.0','+ 0.5','+ 1','+ 1.5' ,'+ 2','+ 2.5','+ 3','+ 3.5','+ 4','+ 4.5','+ 5'];

来自minnumbermaxnumber

var minnumber = 3;
var maxnumber = 5;

var numbers = [];

numbers['-3','-2.5','-2','1.5','1','0.5','0.0','+0.5','+1','+1.5','+2','+2.5','+3','+3.5','+4','+4.5','+5']

2 个答案:

答案 0 :(得分:1)

您可以通过多种方式循环使用,下面我已使用Array.from

var minnumber = 3;
var maxnumber = 5;

var numbers = Array.from({ length: (maxnumber + minnumber) * 2 + 1}, (_,i) => (-minnumber + i * 0.5).toString())

console.log(numbers)

答案 1 :(得分:1)

以0.5的步长从最小数迭代到最大数。

根据您的示例,您似乎还想将数字转换为字符串。

const min = -3;
const max = 5;
const step = 0.5;
const arr = [];

for (let i = min; i <= max; i += step) {
  const str = (i).toString();

   // if you want to push the number to the
   // array instead remove the preceding line
   // and just use arr.push(i)
   arr.push(str);
}

console.log(arr);