简体   繁体   English

从 JavaScript 数组中删除特定索引

[英]Deleting specific index from a JavaScript array

I have a little code written where I am tracking indexes which I have successfully but finding difficulty removing them from the array so I do same with what I am left with.我写了一些代码来跟踪我成功的索引,但发现很难将它们从数组中删除,所以我对剩下的做了同样的事情。

 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])

Output输出

7
5

Expected Output when v[I] is deleted删除 v[I] 时的预期输出

 v = [4,2,3]

Preferably I would like to do something like splice v[i] if v[i] > v[i] -1 and get back v as with the spliced elements.最好我想做一些类似 splice v[i] 如果 v[i] > v[i] -1 的事情,然后像拼接元素一样返回 v。

I first tested point 1 with this similar logic in the command line and it worked but.....;我首先在命令行中使用这种类似的逻辑测试了第 1 点,但它工作正常,但是.....;

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

Output输出

3
```

To delete a specific index of an array you can use the splice like below.要删除数组的特定索引,您可以使用如下拼接。

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"]

However, regarding to the if logic it will be always true because you are testing if a number is greather than itself subtracted by 1. If you are trying to test if the value in current array position is greather than the value in the previous position, so you should so this.但是,关于 if 逻辑,它将始终为真,因为您正在测试一个数字是否大于其自身减去 1。如果您尝试测试当前数组位置中的值是否大于前一个位置中的值,所以你应该这样。

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

Build new array res by eliminating the unwanted elements from array v通过从数组v消除不需要的元素来构建新的数组res

 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);

Try filter method of array object .尝试数组对象的filter 方法。

Instead of removing element from current array you can filter out values you want and get new array by using filter method of 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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