简体   繁体   中英

Splice or remove specific element in an Array

I have a variable of array like this:

dateArray =  [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

Now I wanted to remove the first 12 elements of the dateArray . I tried the code below but it's not working still. I used splice but I don't know what I'm missing.

if(dateArray.length>12){
    for(var d= 0; d <12; d++){
       dateArray.splice(d);
    }
    console.log(dateArray);
}

It outputs empty array: []

what I wanted it to remove only the first 12 and the output should be:

[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

Any help would be much appreciated.

You don't need a for loop to do this

for(var d= 0; d <12; d++){
   dateArray.splice(d);
}

Could be

dateArray.splice(0, 12);

Use splice

 dateArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; dateArray.splice(0,12); document.body.innerHTML = JSON.stringify(dateArray); 

You could also just make a new array with the values you want.

dateArray =  [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

dateArray2 = [];

if(dateArray.length>12){
    for(var i= 0; i < 12; i++){
       dateArray2[i] = dateArray[i];
    }
    console.log(dateArray);
    console.log(dateArray2);
}

Jsfiddle example.

You can use slice function to remove array elements.

slice() : The slice() method returns a shallow copy of a portion of an array into a new array object.

var d2 = dateArray.slice(12, dateArray.length);
console.log(d2); // [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

Try, this code

if(dateArray.length>12){
    dateArray.splice(0, 12);
    console.log(dateArray);
}

source - https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

您要做的就是:

dateArray = dateArray.slice(0,12);


Try datearray.splice(0, 12) . 0 = starting index, 12 = number of elements to remove.
ref: splice()
Good luck!

If you want to remove the 12 elements at one time, you're not using splice() the correct way, here the correct way to use it:

console.log(dateArraysplice(0, 12););

If you want to remove the first element of an array at a time, use the shift() method instead.

if(dateArray.length>12){
    for(var d= 0; d <12; d++){
       dateArray.shift();
    }
    console.log(dateArray);
}

Both method get you this output

[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM