js基础编程-题目18

整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦

编号1到100的一百个人围成一圈,以123123的方式进行报数,数到3的人自动退出圈子,剩下的人继续报数,问最后剩下的人编号是多少?

双指针

function test(n){
  let arr = new Array(n).fill().map((_,i)=>i+1)//flag1
  let num = 1;
  let index = 0;
  while(arr.length > 2){
    if(num !== 3){
      index ++
      num ++  
    }else{
      num = 1
      arr.splice(index,1)
    }
    if(index ===arr.length){index =0}
  }
 return arr
}

flag处:我们有那些需要占位,而上下文中不使用的变量,可以使用下划线表示。

这里扩展下 稀松数组

  • 稀松数组的创建
    Array(仅一个参数) 仅输入一个数,生成有该数长度的空数组(稀松数组)
    new Array(仅一个参数)
console.log(Array(3))//[ <3 empty items> ]
console.log(new Array(3))//[ <3 empty items> ]

ES6有 Array.of 方法,针对数组传一个参数的场景做出了改变

console.log(Array.of(3))// [3]
  • 稀松数组的遍历
    注意:稀松数组是不能遍历的
const arr = Array(3)
console.log(arr.length)//3
for(let i;i<arr.length;i++){//由于不能遍历,此操作无效
  console.log("无效")
  console.log(arr)
}

我们要遍历操作稀松数组,可以想将他填充
方法一:fill() 填充数组

console.log(Array(3).fill())//[ undefined, undefined, undefined ]
console.log(Array(3).fill(1))//[ 1, 1, 1 ]

方法二:... 扩展运算符,将其转化为数组

console.log([...Array(3)])//[ undefined, undefined, undefined ]
上一篇:LaTeX Error: Environment CJKfilltwosides undefined.问题解决方案


下一篇:undefined-冲刺日志(第三天)