如何限制一个函数运行5次?Javascript

lymnna71  于 2023-02-07  发布在  Java
关注(0)|答案(4)|浏览(136)

我试图限制一个函数只能运行5次,但没有成功。所以这个练习的想法是创建一个函数Person(),它会询问一个人的[姓名和年龄],并询问用户信息5次。我的问题是限制这个函数,目前我可以添加尽可能多的用户,而不仅仅是5个。

<body>
    <div class="container">
        <div class="form-box">
            <h1 id="title">Exercise</h1>
            <form>
                <div class="input-group" id="name-field">
                    
                        <input type="text" placeholder="Nome" class='firstName' id="firstName-input">
                    
                   
                        <input type="text" placeholder="Apelido" class="lastName" id="lastName-input">
                    
                    
                        <input type="text" placeholder="Idade" class="age" id="age-input">
                    
                    <div class="btn-field">
                    <button type="button" class="btn-adicionar" id="btn-adicionar" onclick="Person()">Add</button>
                    <button type="button" class="btn-mostrar" id="btn-mostrar" onclick="Show()">Show</button>
                    </div>
                    <p id="p"></p>
                </div>
            </form>
        </div>
    </div>
let Persona = [];
Persona.values = {
    inputs: [],
    labels: {
        n: ' Name: ',
        a: ' Surname: ',
        i: ' Age: ',
    },
};

    function Adicionar() {
        
    
            let firstName = document.getElementById('firstName-input').value;
            let lastName = document.getElementById('lastName-input').value;
            let age = document.getElementById('age-input').value;

            Persona.values.inputs.push({
                firstName: firstName,
                lastName: lastName,
                age: age,
            });
        
        
    }

    function Show() {
        let text = '';
            
            
                for (var i = 0; i < Persona.values.inputs.length; i++) {
        
                    text += "<div class='outrow'>";

                    text += "<span class='lab'>" + Persona.values.labels.n + '</span>';
                    text +=
                        "<span class='outv'>" +
                        Persona.values.inputs[i].firstName +
                        '</span>';
                    text += "<span class='lab'>" + Persona.values.labels.a + '</span>';
                    text +=
                        "<span class='outv'>" +
                        Persona.values.inputs[i].lastName +
                        '</span>';
                    text += "<span class='lab'>" + Persona.values.labels.i + '</span>';
                    text +=
                        "<span class='outv'>" + Persona.values.inputs[i].age + '</span>';
                    text += '</div>';
                }
            
        let result = document.getElementById('p');
        result.innerHTML = text;
    }

我试过使用if语句,但结果还是一样。

function Person() {
        let number = 0
    if (number < 5) {
            let firstName = document.getElementById('firstName-input').value;
            let lastName = document.getElementById('lastName-input').value;
            let age = document.getElementById('age-input').value;

            Persona.values.inputs.push({
                firstName: firstName,
                lastName: lastName,
                age: age,
            });
         number++
        }
        
    }```
tvz2xvvm

tvz2xvvm1#

我认为您根本不需要counter变量,只需选中Persona.values.inputs.length即可。

function Person() {
    if (Persona.values.inputs.length < 5) {
        let firstName = document.getElementById('firstName-input').value;            
        let lastName = document.getElementById('lastName-input').value;
        let age = document.getElementById('age-input').value;

        Persona.values.inputs.push({
            firstName: firstName,
            lastName: lastName,
            age: age,
        });
    }
}

还可以将输入值直接分配给对象,避免创建不必要的变量

function Person() {
    if (Persona.values.inputs.length < 5) {
        Persona.values.inputs.push({
            firstName: document.getElementById('firstName-input').value,
            lastName: document.getElementById('lastName-input').value,
            age: document.getElementById('age-input').value,
        });
    }
}
9o685dep

9o685dep2#

我们在函数中添加了计数器变量number,所以每次调用这个函数时,number都会被重置为零,这对下面的条件没有影响。实际上,我们需要将number变量声明为全局变量,这样它就不会重置:

let number = 0 

function Person() {
  if(number < 5) {...}
  number++
}
jexiocij

jexiocij3#

你可以使用一个计数器来跟踪函数被调用的次数,如果达到了限制,就提前返回。

let counter = 0;

function Person() {
  if (counter === 5) {
    return;
  }

  const name = prompt("Enter your name:");
  const surname = prompt("Enter your surname:");
  const age = prompt("Enter your age:");

  console.log(`Name: ${name} Surname: ${surname} Age: ${age}`);
  counter++;
}

这样,函数Person将在第5次之后停止运行。

bq9c1y66

bq9c1y664#

如果出于某种原因需要在函数本身上跟踪这一点,可以使用closure

let Person = (function () {
  let number = 1;
  return function () {
     if(number <= 5) {
        console.log(`Called ${number} times`);
     }
     number++
  }
})();
for (let i = 0; i < 100;i++) Person();

这定义了一个函数沿着该函数外部的变量。

相关问题