[英]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
. 现在,我想删除
dateArray
的前12个元素。 I tried the code below but it's not working still. 我尝试了以下代码,但仍无法正常工作。 I used
splice
but I don't know what I'm missing. 我使用了
splice
但不知道缺少什么。
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: 我想要它仅删除前12个,输出应为:
[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循环即可执行此操作
for(var d= 0; d <12; d++){
dateArray.splice(d);
}
Could be 可能
dateArray.splice(0, 12);
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);
}
You can use slice
function to remove array elements. 您可以使用
slice
功能删除数组元素。
slice() : The slice()
method returns a shallow copy of a portion of an array into a new array object. slice() :
slice()
方法将数组的一部分的浅表副本返回到新的数组对象中。
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 来源-https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
您要做的就是:
dateArray = dateArray.slice(0,12);
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: 如果要一次删除这12个元素,则说明您使用的不是正确的
splice()
方法,这里是使用它的正确方法:
console.log(dateArraysplice(0, 12););
If you want to remove the first element of an array at a time, use the shift()
method instead. 如果要一次删除数组的第一个元素,请改用
shift()
方法。
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]
[31,28,31,30,31,30,31,31,30,31,30,31]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.