[英]what is the correct way to splice an array using for loop, having nested if conditions
i am facing this issue of splicing an array.i checked out all the examples i could find but all in vein.我正面临拼接数组的问题。我检查了我能找到的所有示例,但都在脉络中。 the troubles are these nested if conditions inside the for loop.i am doing i-- but not able to go ahead.
麻烦是这些嵌套的 if 条件在 for 循环中。我正在做我 - 但无法提前 go。 can anybody help me out and explain the approach.i am adding a snippet.
谁能帮我解释一下方法。我正在添加一个片段。 the prob is that, whenever i don't do the i-- operation, and splice the array, alternate removal of elements happens but upon adding the i--, i am not able to proceed any further.
问题是,每当我不执行 i-- 操作并拼接数组时,就会交替删除元素,但是在添加 i-- 时,我无法继续进行。 i tried --i, but now i am confused as to what i am doing wrong.
我试过--i,但现在我对自己做错了什么感到困惑。 here m is an array of number from 1 to 20 serially.
这里 m 是一个从 1 到 20 的数字数组。 having length 20.
长度为 20。
var k=13;
for (var i = 0; i < m.length; i++) {
if (m[i] < k) {
if (i != 0 && i != m.length) {
m.splice(i, 1);
}
if (i == 0) {
m.splice(i, 1);
}
i--;
}
}
From what I can read, you want to filter
out all elements lesser than 13. You can do the same by using filter()
in javascript据我所知,您想过
filter
所有小于 13 的元素。您可以通过在 javascript 中使用filter()
来做同样的事情
const filterLimit = 13;
// Here filteredList is the list of all elements lesser than filterLimit
const filteredList = m.filter(item => item >= filterLimit);
Example:例子:
const filterLimit = 13; const unFilteredList = [1, 13, 14, 2, 5, 33]; const filteredList = unFilteredList.filter(item => item >= filterLimit); console.log(filteredList);
There is an error in this approach and that's you must not change the parameter (i)
of the loop inside the loop这种方法有一个错误,那就是你不能在循环内更改循环的参数
(i)
You can use while
instead:您可以改用
while
:
var k=13;
var i=0;
while (i < m.length){
if(m[i] < k){
m.splice(i, 1);
}else{
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.