从JavaScript数组中删除特定索引

时间:2020-03-13 16:05:14

标签: javascript arrays sorting indexing array-splice

我写了一些代码来跟踪成功的索引,但是发现很难从数组中删除它们,所以我对剩下的东西也做同样的事情。

 var v = [4, 7, 2,5, 3] 
 var f = []
 for (let i = 1; i < v.length; i += 2){
/*(point1)this line doesn't seem to work*/
 if (v[i] > v[i] - 1)
/*(point 2) Instead of console.log I want to delete every of v[i] */
console.log(v[i])

输出

7
5

删除v [I]时的预期输出

 v = [4,2,3]

优选地,如果v [i]> v [i] -1,我想做类似拼接v [i]的操作,并像拼接元素一样取回v。

我首先在命令行中使用类似的逻辑测试了点1,但是它起作用了,但是.....;

   if ((b[1] -1) > b[0]){console.log(b[2])}

输出

3
```

3 个答案:

答案 0 :(得分:0)

要删除数组的特定索引,可以使用如下所示的接头。

var fruits = ["apple", "orange", "avocado", "banana"];
//remove one element starting from index 2
var removed = fruits.splice(2, 1);
//fruits is ["apple", "orange", "banana"]
//removed is ["avocado"]

但是,关于if逻辑,它将始终为真,因为您正在测试一个数字是否比其自身大1。 如果要测试当前数组位置中的值是否大于前一个位置中的值,则应该这样做。

if (v[i] > v[i-1])

答案 1 :(得分:0)

通过消除数组res中不需要的元素来构建新的数组v

var v = [4, 7, 2, 5, 3];
var res = [];
res.push(v[0]);
for (let i = 1; i < v.length; i += 1) {
  if (v[i - 1] > v[i]) {
    res.push(v[i]);
  }
}

console.log(res);

答案 2 :(得分:0)

尝试使用array object的过滤器方法。

代替从当前数组中删除元素,您可以过滤出所需的值并使用数组对象的filter方法获得新数组。

var arr = [0, 1, 2, 3];

var filteredArr = arr.filter(function(element, currentIndex, arrObj) {
   //currentIndex and arrObj can be used to form your desired condition but they are 
  //optional parameter
  // below is the filter condition to be applied on each element
  return element > 0;
});

console.log('filteredArr will have all the elements of the array which satisfies the filter condition:', filteredArr);