如何删除和对象和数组

时间:2016-01-29 13:28:42

标签: javascript arrays object

提前感谢您的帮助。我已经尝试了两天如何删除存储在数组中的对象而我却得不到它。只是在论坛上阅读并尝试,但没有任何作用。

<head>

    <style>
    </style>
    <script type="text/javascript">
        //Global Array to saved more than one object without having to declare all of them
        var car = {};
        var i;
        var numRecords2 = 0;
        var doors;
        var outOfDateInsurance;
        var contRecords = -1;

        // Class Cars
        function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
        {
            this.record = record;
            this.brand = brand;
            this.color = color;
            this.doors = doors;
            this.insurance = insurance;
            this.outOfDateInsurance = outOfDateInsurance;
        }

        //To validate number of the doors. It has to be 3 or 5
        function validateDoors()
        {
            doors = prompt("Number of doors");
            doors = parseInt(doors);

            if (isNaN(doors) === false && (doors == 3 || doors == 5))
            {
                return;
            }
            else
            {
                alert("Wrong character. Please, set 3 or 5");
                validateDoors();
            }
        }

        //To validate date's format 
        function validateFormatDate(outOfDateInsurance)
        {
            var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
            if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //To check if the date is in the calendar
        function realDate(outOfDateInsurance)
        {
            var fechaf = outOfDateInsurance.split("/");
            var d = fechaf[0];
            var m = fechaf[1];
            var y = fechaf[2];
            return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
        }

        //To validate the date is over today
        function validateAboveDate(outOfDateInsurance)
        {
            var datef = outOfDateInsurance.split("/");
            var d = datef[0];
            var m = datef[1];
            var y = datef[2];

            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth()+1; //January is 0!
            var yyyy = today.getFullYear();
            if(dd<10)
            {
                dd='0'+dd
            } 
            if(mm<10)
            {
                mm='0'+mm
            } 
            var today = dd+'/'+mm+'/'+yyyy;
            var todayf = today.split("/");
            var dt = todayf[0];
            var mt = todayf[1];
            var yt = todayf[2];

            if ((d > dt) && (m >= mt) && (y >= yt))
            {
                return true;
            }
            else
            {
                if ((d = dt) && (m > mt) && (y >= yt))
                {
                    return true;
                }
                else
                {
                    if ((d < dt) && (m > mt) && (y >= yt))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }

        //To validate the date's is right
        function checkingDate()
        {
            outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
            if(validateFormatDate(outOfDateInsurance))
            {
                if(realDate(outOfDateInsurance))
                {
                    if (validateAboveDate(outOfDateInsurance))
                    {
                        alert("Record has been introduced into the system");
                    }
                    else
                    {
                        alert("You have introduced an incorrect Insurance's End date");
                        checkingDate();
                    }
                }
                else
                {
                    alert("You have introduced an incorrect Insurance's End date");
                    checkingDate();
                }
            }
            else
            {
                alert("You have introduced an incorrect Insurance's End date");
                checkingDate();
            }
        }

        //To create objects
        function addCar()
        {
            var numRecords = prompt("How many records do you want to introduce to the system?");
            numRecords = parseInt(numRecords);

            if (isNaN(numRecords) === false)
            {
                var istart = contRecords + 1;
                var iend = numRecords2 + numRecords;

                //problema añadiendo cars porque reemplaza si no lo hago todo de una vez
                for (i = istart; i < iend; i++)
                {
                    contRecords++;
                    var record = contRecords;
                    var brand = prompt("Car's Brand");
                    var color = prompt("Car's Color");
                    validateDoors();
                    var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
                    if (insurance === true)
                    {
                        insurance = "Yes";
                        checkingDate();
                    }
                    else
                    {
                        insurance = "No";
                        alert("Record has been introduced into the system");
                    }

                    //CONSTRUCTOR We are creating the object car in the Class Cars
                    car[i] = new Cars(record, brand, color, doors, insurance, outOfDateInsurance);
                }
                numRecords2 = numRecords2 + numRecords;
            }
            else
            {
                alert("Please, introduce the number of the records you want to introduce");
                addCar();
            }
        }

        //To display the objects created
        function displayCar()
        {
            document.getElementById("container").innerHTML = "";
            for (i = 0; i < numRecords2; i++)
            {
                //we are creating an element <p>
                var parag = document.createElement('p');
                parag.id = "paragraph" + i;
                //we are creating an element <br>
                var br = document.createElement('br');
                //we are creating a text node
                var textRecord = document.createTextNode("Record: " + car[i].record);
                var textBrand = document.createTextNode("Brand: " + car[i].brand);
                var textColor = document.createTextNode("Color: " + car[i].color);
                var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
                var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
                if (car[i].insurance === "Yes")
                {
                    var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
                }
                else
                {
                    var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
                }

                //we are adding the text nodes created to the <p>
                parag.appendChild(textRecord);
                //We are creating a clone from a node to have multiple break lines
                parag.appendChild(br.cloneNode());
                parag.appendChild(textBrand);
                parag.appendChild(br.cloneNode());
                parag.appendChild(textColor);
                parag.appendChild(br.cloneNode());
                parag.appendChild(textDoors);
                parag.appendChild(br.cloneNode());
                parag.appendChild(textInsurance);
                parag.appendChild(br.cloneNode());
                parag.appendChild(textOutOfDateInsurance);
                //we are adding the whole <p> with the text nodes into the div created in the html
                document.getElementById("container").appendChild(parag);
            }
        }

        function deleteCar()
        {
            car[0] = null;
            car.splice(0);
            for (i = 0; i <= contRecords; i++)
            {
                alert(car[i]);
            }
            //if (contRecords >=0)
            //{
            //    var numRecordToDelete = prompt("Introduce the record's number you want to delete");
            //    numRecordToDelete = parseInt(numRecordToDelete);
            //    if (isNaN(numRecordToDelete) === false)
            //    {
            //        //var i = numRecordToDelete;
            //        //
            //        //    alert('Record: ' + i);
            //        //if(car[i].record === 'Record: ' + i)
            //        //{
            //        //    alert('Record: ' + i);
            //        //    car.splice(i,1);
            //        //    return false;
            //        //}
            //        car.shift();
            //        document.getElementById("container").innerHTML = car;
            //    }
            //    else
            //    {
            //        alert("The character you have introduce is not a number");
            //        deleteCar();
            //    }
            //}
            //else
            //{
            //    alert("There are no any record to delete");
            //    return;
            //}
        }
    </script>

</head>

<body>

    <h1 style="text-align: center;">WELLCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
    <br><br>

    <!-- Button to create the object car -->
    <input type="button" value="Add Car" onclick="addCar()">
    <!-- Button to display the objects created -->
    <input type="button" value="See Cars" onclick="displayCar()">
    <input type="button" value="Delete Cars" onclick="deleteCar()">
    <BR>
    <hr>
    <BR>
    <!-- Div which information's objects is going to be displayed -->
    <div id="container"></div>

</body>

所以事实是,我正在像BBDD一样向数组添加对象,我不知道如何从数组中删除一个对象并重新组织数组位置中的其他对象,如果我删除了元素的数组编号为2,那么,数字3将是第二个,而第四个将是第三个,等等...

非常感谢,有任何疑问,请告诉我。我非常感谢你的帮助。

4 个答案:

答案 0 :(得分:0)

您可以使用Array.splice()从数组中删除条目。 Link

car.splice(0,1);

答案 1 :(得分:0)

我应该使用一组对象。实际上你使用一个对象如何在多少个对象的数组。通过这种方式可以更容易地添加,查看和删除实际的汽车。

if(n == null)
{

}

添加时:

car = [];

除此之外,我建议您在添加或删除汽车时,客户端的刷新数据可以查看更改并刷新删除的记录号。

当你拼接一个数组元素时,后面的其他元素会移动-1。因此,必须在最后调用displayCar()。

car.push(new Cars(record, brand, color, doors, insurance, outOfDateInsurance));

答案 2 :(得分:0)

我相信我明白你在寻找什么,所提供的例子应该解决这个问题,如果不让我知道的话。

  <script>
  var collectionOfObjects = [];
  collectionOfObjects.push({name: "anObject1"});
  collectionOfObjects.push({name: "anObject2"});
  collectionOfObjects.push({name: "anObject3"});
  collectionOfObjects.push({name: "anObject4"});

  console.log("collectionOfObjects initial state");
  console.log(collectionOfObjects);
  console.log("deleteing 2nd member - this will delete the object even if other things have reference to it and not just remove it from the collection");
  console.log("deleteing 2nd member - it will croupt the length of the array but we can fix that");
  delete collectionOfObjects[2];
  collectionOfObjects = collectionOfObjects.sort();
  collectionOfObjects.length = collectionOfObjects.length - 1
  console.log("collectionOfObjects after delete");
  </script>

另一方面,我注意到你也可以这样做:

  //To validate date's format 
  function validateFormatDate(outOfDateInsurance)
  {
      var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
      return outOfDateInsurance.match(RegExPattern) && (outOfDateInsurance!='')
  }

答案 3 :(得分:0)

//Global Array to saved more than one object without having to declare all of them
var car = [],
    doors,
    outOfDateInsurance;


// Class Cars
function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
{
  this.record = record;
  this.brand = brand;
  this.color = color;
  this.doors = doors;
  this.insurance = insurance;
  this.outOfDateInsurance = outOfDateInsurance;
}

//To validate number of the doors. It has to be 3 or 5
function validateDoors()
{
  doors = prompt("Number of doors");
  doors = parseInt(doors);

  if (isNaN(doors) === false && (doors == 3 || doors == 5))
  {
    return;
  }
  else
  {
    alert("Wrong character. Please, set 3 or 5");
    validateDoors();
  }
}

//To validate date's format 
function validateFormatDate(outOfDateInsurance)
{
  var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
  if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
  {
    return true;
  }
  else
  {
    return false;
  }
}

//To check if the date is in the calendar
function realDate(outOfDateInsurance)
{
  var fechaf = outOfDateInsurance.split("/");
  var d = fechaf[0];
  var m = fechaf[1];
  var y = fechaf[2];
  return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}

//To validate the date is over today
function validateAboveDate(outOfDateInsurance)
{
  var datef = outOfDateInsurance.split("/");
  var d = datef[0];
  var m = datef[1];
  var y = datef[2];

  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!
  var yyyy = today.getFullYear();
  if(dd<10)
  {
    dd='0'+dd
  } 
  if(mm<10)
  {
    mm='0'+mm
  } 
  var today = dd+'/'+mm+'/'+yyyy;
  var todayf = today.split("/");
  var dt = todayf[0];
  var mt = todayf[1];
  var yt = todayf[2];

  if ((d > dt) && (m >= mt) && (y >= yt))
  {
    return true;
  }
  else
  {
    if ((d = dt) && (m > mt) && (y >= yt))
    {
      return true;
    }
    else
    {
      if ((d < dt) && (m > mt) && (y >= yt))
      {
        return true;
      }
      else
      {
        return false;
      }
    }
  }
}

//To validate the date's is right
function checkingDate()
{
  outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
  if(validateFormatDate(outOfDateInsurance))
  {
    if(realDate(outOfDateInsurance))
    {
      if (validateAboveDate(outOfDateInsurance))
      {
        alert("Record has been introduced into the system");
      }
      else
      {
        alert("You have introduced an incorrect Insurance's End date");
        checkingDate();
      }
    }
    else
    {
      alert("You have introduced an incorrect Insurance's End date");
      checkingDate();
    }
  }
  else
  {
    alert("You have introduced an incorrect Insurance's End date");
    checkingDate();
  }
}

//To create objects
function addCar()
{
  var numRecords = prompt("How many records do you want to introduce to the system?");
  numRecords = parseInt(numRecords);

  if (isNaN(numRecords) === false)
  {
    var iend = numRecords;

    //problema añadiendo cars porque reemplaza si no lo hago todo de una vez
    for (var i = 0; i < iend; i++)
    {
      var brand = prompt("Car's Brand");
      var color = prompt("Car's Color");
      validateDoors();
      var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
      if (insurance === true)
      {
        insurance = "Yes";
        checkingDate();
      }
      else
      {
        insurance = "No";
        alert("Record has been introduced into the system");
      }

      //CONSTRUCTOR We are creating the ARRAY car in the Class Cars
      car.push(new Cars(car.length + 1, brand, color, doors, insurance, outOfDateInsurance));
    }
  }
  else
  {
    alert("Please, introduce the number of the records you want to introduce");
    addCar();
  }
  displayCar();
}

//To display the objects created
function displayCar()
{
  document.getElementById("container").innerHTML = "";
  for (var i = 0; i < car.length; i++)
  {
    //we are creating an element <p>
    var parag = document.createElement('p');
    parag.id = "paragraph" + i;
    //we are creating an element <br>
    var br = document.createElement('br');
    //we are creating a text node
    var textRecord = document.createTextNode("Record: " + car[i].record);
    var textBrand = document.createTextNode("Brand: " + car[i].brand);
    var textColor = document.createTextNode("Color: " + car[i].color);
    var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
    var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
    if (car[i].insurance === "Yes")
    {
      var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
    }
    else
    {
      var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
    }

    //we are adding the text nodes created to the <p>
    parag.appendChild(textRecord);
    //We are creating a clone from a node to have multiple break lines
    parag.appendChild(br.cloneNode());
    parag.appendChild(textBrand);
    parag.appendChild(br.cloneNode());
    parag.appendChild(textColor);
    parag.appendChild(br.cloneNode());
    parag.appendChild(textDoors);
    parag.appendChild(br.cloneNode());
    parag.appendChild(textInsurance);
    parag.appendChild(br.cloneNode());
    parag.appendChild(textOutOfDateInsurance);
    //we are adding the whole <p> with the text nodes into the div created in the html
    document.getElementById("container").appendChild(parag);
  }
}

function deleteCar()
{
  if (car.length >0)
  {
    var numRecordToDelete = prompt("Introduce the record's number you want to delete");
    numRecordToDelete = parseInt(numRecordToDelete);
    if (isNaN(numRecordToDelete) === false)
    {
      alert('Record: ' + numRecordToDelete);
      if(numRecordToDelete >= car.length)
      {
        alert('Record: ' + numRecordToDelete);
        car.splice(numRecordToDelete - 1,1);
        displayCar();
        return false;
      }
      else {
        alert("Record not exist");
        deleteCar();
      }
    }
    else
    {
      alert("The character you have introduce is not a number");
      deleteCar();
    }
  }
  else
  {
    alert("There are no any record to delete");
    return;
  }
}
<h1 style="text-align: center;">WELCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
<br><br>

<!-- Button to create the object car -->
<input type="button" value="Add Car" onclick="addCar()">
<!-- Button to display the objects created -->
<input type="button" value="See Cars" onclick="displayCar()">
<input type="button" value="Delete Cars" onclick="deleteCar()">
<BR>
<hr>
<BR>
<!-- Div which information's objects is going to be displayed -->
<div id="container"></div>