如何打印数组中数字重复的次数? JS

问题描述 投票:0回答:1

我正在尝试解决这个练习:

编写一段 JavaScript 代码,要求用户输入一个数字,然后打印该数字在数组中出现的次数。

我用

parseFloat
来做这件事,这样我就可以用
<input />
从用户那里获取字符串并将其更改为数字,然后我用数字声明我自己的数组。

function repeatNumber() {
    const number = parseFloat(document.getElementById("number").value);
    const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    let compare = false;

    for (let i = 0; i < number.length; i++) {
        if (myArray[i] === number) {
            compare = true;
        }
    }

    //compare is my id in a p tag where i'll show the result
    const repeating = document.getElementById("compare");

    repating.textContent = "Is your number in my array ?" + compare;
}
javascript arrays function for-loop dom
1个回答
0
投票

也许试试这个

function repeatNumber(){

    const number = parseFloat(document.getElementById("number").value);
    const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    let compare= false;
    var count = 0;
   
    for(let i=0; i < myArray.length; i++){
     
    
    if( myArray[i] === number){
            count++;
            compare=true;
    }

}   
const repeating = document.getElementById("compare"); //compare is my id in a p tag where i'll show the result
repating.textContent = "Is your number in my array ?" + compare;
console.log(count);
    
}

© www.soinside.com 2019 - 2024. All rights reserved.