簡體   English   中英

從 JavaScript 數組中刪除特定索引

[英]Deleting specific index from a JavaScript array

我寫了一些代碼來跟蹤我成功的索引,但發現很難將它們從數組中刪除,所以我對剩下的做了同樣的事情。

 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]

最好我想做一些類似 splice v[i] 如果 v[i] > v[i] -1 的事情,然后像拼接元素一樣返回 v。

我首先在命令行中使用這種類似的邏輯測試了第 1 點,但它工作正常,但是.....;

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

輸出

3
```

要刪除數組的特定索引,您可以使用如下拼接。

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

通過從數組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);

嘗試數組對象的filter 方法。

您可以使用數組對象的 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