有沒有辦法生成n它們之間的空間逐漸增長的數字,并且該空間在最小值和最大值之間變化?這些數字的域并不重要。
我想像這樣呼叫一個函式:
const serie = computeSerie(n, minSpace, maxSpace)
// domain is not important, for example [1, infinity] but also [0, 1], what you prefer
const serie1 = computeSerie(5, 1, 1) // [1, 2, 3, 4, 5]
const serie2 = computeSerie(5, 2, 2) // [1, 3, 5, 7, 9]
const serie3 = computeSerie(5, 1, 4) // [1, ...] I don't know, I suppose to use a pow math function (?)
const serie4 = computeSerie(7, 1, 6) // [1, 2, 4, 8, 13, 18, 24]
視覺上:
serie1: |-|-|-|-|
serie2: |--|--|--|--|
serie3: |-|???|--|
serie4: |-|--|---|----|-----|------|
我不知道如何實作這一點,也許 d3 可能有用,但如何實作?
非常感謝每一個提示
uj5u.com熱心網友回復:
這應該有效,但如果您的minSpace和maxSpace值與n您的值不匹配,您也會得到小數值。(可以Math.floor/ceil/round為那些做一個嗎?)
function computeSerie(n, minSpace, maxSpace) {
const step = (maxSpace - minSpace) / (n - 2)
const arr = []
const startAt = 1
arr.push(startAt)
for (let i = 1; i < n; i ) {
arr.push(arr[i - 1] minSpace (i - 1) * step)
}
return arr
}
console.log(computeSerie(5, 1, 1)) // [1, 2, 3, 4, 5]
console.log(computeSerie(5, 2, 2)) // [1, 3, 5, 7, 9]
console.log(computeSerie(5, 1, 4)) // [1, 2, 4, 7, 11]
console.log(computeSerie(7, 1, 6)) // [1, 2, 4, 7, 11, 16, 22]
// will get fractional values for this
console.log(computeSerie(7, 1, 5)) // [1, 2, 3.8, 6.4, 9.8, 14, 19]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312861.html
標籤:javascript 数学 d3.js
