gpt4 book ai didi

javascript - 数组打印多次

转载 作者:行者123 更新时间:2023-12-03 02:36:42 27 4
gpt4 key购买 nike

我试图打印数组中多次出现的每个元素,以及它们所在的索引。例如:高(编号):2,索引:0但是,我只希望它每个索引打印一次。抱歉,解释不好,而且是挪威语!

<!Doctype html>
<HTML lang="no">

<head>
<meta charset="utf-8">
<title>#</title>
<script>
window.onload = oppstart;

function oppstart() {
var heltall = [2, 3, 4, 3, 5, 2, 1, 4, 2, 1, 4, 2, 3, 4, 5, 6];
var utskrift = "-- \n";

for (j = 0; j < heltall.length; j++) {
var talletViSkalTelle = heltall[j];
for (i = 0; i < heltall.length; i++) {
if (heltall[i] == talletViSkalTelle) {
utskrift += "Tall: " + talletViSkalTelle + ", index: " + i + "\n";
}
}
}
print(utskrift);
}

function print(text) {
var el = document.getElementById("utskrift");
el.innerText = text;
//el = element//
}

</script>
</head>

<body>

<p id="utskrift"></p>

</body>

最佳答案

创建一个数组来存储您已经遍历过的数字,然后在再次迭代之前检查该数组是否已存储下一个数字。

请参阅下面的工作片段

<!Doctype html>
<HTML lang="no">

<head>
<meta charset="utf-8">
<title>#</title>
<script>
window.onload = oppstart;
var pushed = [];

function oppstart() {
var heltall = [2, 3, 4, 3, 5, 2, 1, 4, 2, 1, 4, 2, 3, 4, 5, 6];
var utskrift = "-- \n";

for (j = 0; j < heltall.length; j++) {
var talletViSkalTelle = heltall[j];
if(!check(talletViSkalTelle)){
pushed.push(talletViSkalTelle);
for (i = 0; i < heltall.length; i++) {
if (heltall[i] == talletViSkalTelle) {
utskrift += "Tall: " + talletViSkalTelle + ", index: " + i + "\n";
}
}
}
}
print(utskrift);
}

function print(text) {
var el = document.getElementById("utskrift");
el.innerText = text;
//el = element//
}

function check(num){
for(var i = 0; i<pushed.length; i++){
if(num === pushed[i]){
return true;
}
}
return false;
}

</script>
</head>

<body>

<p id="utskrift"></p>

</body>

关于javascript - 数组打印多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48516626/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com