如何设置slice(); push(); splice()方法的限制?

时间:2016-02-24 12:19:05

标签: javascript arrays

我知道:

  • with splice()我可以在数组中添加项目
  • with pop()我可以删除数组中的最后一项
  • 使用push()我可以在数组中添加项目

现在我想知道如何设置限制。例如,我希望当用户点击时,他应该能够实现数组方法的这种性能 slice();push();splice()只有一两次。如何才能使用这种数组方法两次?

代码:

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits;

    function myFunction() {
        fruits.push("Kiwi");
        document.getElementById("demo").innerHTML = fruits;
    }
</script>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits;

    function myFunction() {
        fruits.pop();
        document.getElementById("demo").innerHTML = fruits;
    }
</script>

4 个答案:

答案 0 :(得分:1)

var limit = 2;
if (limit) {
    fruits.pop();
    limit--;
}

答案 1 :(得分:1)

你的意思是:

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
<p id="error"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

var limit = 2;
function myFunction() {
  if(limit > 0) {
    limit = limit - 1 ;
    fruits.push("Kiwi");
    document.getElementById("demo").innerHTML = fruits;
  }
  else {
    
    document.getElementById("error").innerHTML = "Your limit reached";
  }
}
</script>

答案 2 :(得分:0)

您可以通过设置计数器来尝试这样的事情。

<script>
var pushCounter = 0;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    if(pushCounter<2)
    {
     fruits.push("Kiwi");
     pushCounter++;    
    }
    document.getElementById("demo").innerHTML = fruits;
}
</script>

答案 3 :(得分:0)

只需对每个操作的限制验证fruits数组的长度,并在向用户发送警报消息时忽略操作。

JS CODE:

var limit = 1;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
   if(fruits.length === limit){
       alert('limit reached cant pop the items anymore!!!');
       return;
   }
   fruits.pop();
   document.getElementById("demo").innerHTML = fruits;
}

myFunction(); //["Banana", "Orange", "Apple"];
myFunction(); //["Banana", "Orange"];
myFunction(); //["Banana"];
myFunction(); //pop operation denied