问题描述
我需要有关 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']))