当数组项超过10时,我试图删除数组中的前5项,因为我的数组继续在setInterval方法中添加项。
function checkArray(array,limit,toshow){
var length = array.length;
if(length > limit){
var splicedArry = _.drop(array1,toshow);
array = splicedArry;
}
return array;
}请检查一下小提琴
发布于 2018-09-14 10:11:53
下面是您的JSfiddle的全部工作代码(使用Vanilla ):
var arrayEl = [];
var count =0;
setInterval(function(){
count = ++count;
arrayEl.push(count);
},1000)
setInterval(function() {
// modify array by reference
checkArray(arrayEl,10,5)
// print the contents of modified array
console.log(arrayEl)
}, 1100)
function checkArray(array,limit,toshow){
// splice takes 2 arguments to modify an array (people often confuse it with `slice`
if (array.length > limit) array.splice(0, toshow);
}Lodash _.drop创建了一个新的数组,所以整个代码如下所示:
var arrayEl = [];
var count =0;
setInterval(function(){
count = ++count;
arrayEl.push(count);
},1000)
setInterval(function() {
// you must assign the returned value to your original array
arrayEl = checkArray(arrayEl,10,5)
console.log(arrayEl)
}, 1100)
function checkArray(array,limit,toshow){
if (array.length > limit) return _.drop(array, toshow);
return array;
}发布于 2018-09-14 10:01:02
您可以使用香草js:
let checkArray = (array, limit, toShow) => {
if (array.length > limit) array.splice(toShow);
}发布于 2018-09-14 10:13:29
与其使用_.drop()方法,不如使用JavaScript的本机方法,它以要删除的索引和要删除的项数作为参数。
因此,在您的函数中,您会这样称呼它:
array.splice(0, toshow)因此,它从toshow中删除第一个array元素,其中toshow是要删除的项数。
以下是您的功能:
function checkArray(array, limit, toshow) {
if (array.length > limit) {
array.splice(0, toshow);
}
return array;
}演示:
这是用正确的函数更新的代码:
var arrayEl = [];
var count = 0;
setInterval(function() {
count = ++count;
arrayEl.push(count);
}, 1000)
setInterval(function() {
console.log(checkArray(arrayEl, 10, 5))
}, 1100);
function checkArray(array, limit, toshow) {
if (array.length > limit) {
array.splice(0, toshow);
}
return array;
}
https://stackoverflow.com/questions/52329480
复制相似问题