数组拍平(拉平,降维)

flat,参数是层级数,如果不知道,参数传递Infinity
eval() 函数 console.log(eval([${[1, [2, 3, [4]]] + ''}])) // [1,2,3,4]
image.png
image.png

输入某个数,返回连续递增的可以达到这个数的数组

image.png

  1. function fn (count) {
  2. let res = []
  3. let middle = Math.ceil(count / 2);
  4. for (let i = 1; i <= middle; i++) {
  5. for (let j = 2; ; j++) {
  6. // 求出累加的和
  7. let total = (i + (i + j - 1)) * (j / 2)
  8. if (total > count) {
  9. break
  10. } else if (total === count) {
  11. res.push(createArr(i, j))
  12. break
  13. }
  14. }
  15. }
  16. return res
  17. }
  18. function createArr (n, l) {
  19. let arr = new Array(l).fill(null),
  20. temp = []
  21. arr[0] = n
  22. arr = arr.map((item, index) => {
  23. if (item === null) {
  24. item = temp[index - 1] + 1
  25. }
  26. temp.push(item)
  27. return item
  28. })
  29. return arr
  30. }
  31. console.log(fn(10));