微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在javascript中没有for循环的情况下编写以下代码

如何解决如何在javascript中没有for循环的情况下编写以下代码

我需要有关 javascript 中以下程序的帮助

一个没有任何循环语句的函数,它接受一个数组并产生一个新数组,该数组等于初始数组,其中第 i 个元素(从 1 开始)重复 i 次。

我可以在 for 循环中编写代码,只需要在没有循环的情况下编写代码

<html>
<h3>for this tab manipulation,so that you cannot edit all tabs connected to this site,you need to kNow the <bold>KEY</bold> of someone else's tab</h3>
<p>your key is <bold>\</bold></p>
<input placeholder="enter other tab's key here" id="inp" />
<select id="currentEvent">
  <option value="" disabled selected>Current Event</option>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>
<button type="button" onclick="GetSelectedText()">Push Changes</button>
<h4 id="selectedEvent"></h4>
<script>
//loop checking for incoming changes (empty input("") means it would me treated as no input)
var select=document.getElementById("selectedEvent");
(async()=>{
  var options={
    method:'POST',headers:{'receive':'true','key':key}
  }
  while(true){
    let x=await fetch(location.href,options)
    let text=await x.text()
    if(text){select.innerHTML=text}
  }
})()
//Now for the button
function GetSelectedText() {
  var e = document.getElementById("currentEvent");
  var result = e.options[e.selectedindex].text;
  select.innerHTML = result;
  //sends an outgoing request that will edit the other tab
  var xhr=new XMLHttpRequest()
  xhr.open('POST',location.href,true)
  var inp=document.getElementById('inp')
  xhr.setRequestHeader('pw',inp.value)
  xhr.setRequestHeader('inp',result)
  xhr.send()
}
//Now for a listener that will attempt to delete the key from the server as it closes
window.onbeforeunload = async function(){
  await fetch(location.href,{method:'POST',headers:{'end':'yes'}})
  //put return in front of the 'await' word in line above
  //and a confirm would appear when you try to close
}
</script>
</html>

解决方法

这可以是另一种方法:

function stretched(a) {
    const stretchedArray = [];
    for (let [index,item] of a.entries()) {
      stretchedArray.push(...(new Array(index + 1).fill(item)))
    }
    return stretchedArray;
}

console.log(stretched(['a','b','c']))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。