2016-09-24 59 views
1

迭代後,在數組對象例如:的Javascript目前唯一的對象

[x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. 
x1 compares itself to x0, x2 and x3. And so on... 

[x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. 
x1 compares itself to x2 and x3 only. 
x2 only compares itself to x3. 
x3 does not need to do any comparison at all. 

基本上我希望只有一個辦法遍歷數組,每當前元素後面的元素被忽略。

for (var i = 0; i < boids.length; i++) { 
//boids is an array containing elements "boid" 


    var d = distSquared(this.position.x, this.position.y, boids[i].position.x, boids[i].position.y); 
     //get distance between current boid and all other boids in array. 
     //Looking to change this to get distance between current boid and all other boids infront of this element in the array. 

    if (boids[i] == this) { //if the boid being compared is to its own self, skip it. 
      continue; 
     } 
} 

我該如何去實現這樣的結構?

+0

歡迎來到SO!只是一個指針,我只看到1 for循環。你能分享比較是如何完成的嗎? – Rajesh

+0

所以即使'this'也會出現在'boids'數組中。所以只需在數組中搜索'this'的索引並相應地初始化'i'。 – Rajesh

回答

1

什麼你正在尋找排除一種或多種元素是這樣的:

var a = [1,2,3,4]; 
 

 
for(var i=0; i<a.length; i++){ 
 
    for(var j=i+1; j<a.length; j++){ 
 
    console.log(i,j) 
 
    } 
 
}

0

您可以使用Array.prototype.filter()從陣列

var arr = [1,2,3,4,5]; 
 
for (var i = 0; i < arr.length; i++) { 
 
    var curr = arr[i]; 
 
    var not = arr.filter(function(_, index) { 
 
    return index != i 
 
    }); 
 
    console.log(`curr:${curr}`); 
 
    not.forEach(function(el) { 
 
    console.log(`${curr} is not ${el}`) 
 
    }) 
 
}

+0

感謝您的回覆,但我不想刪除列表中當前的檢查元素,而是刪除它後面的所有元素。基本上我正在尋找只能以一種方式遍歷數組。 – Carrein

0

你可能會這樣做。塑造如何比較取決於你。

var arr = [1,2,3,4,5], 
 
result = arr.map((e,i,a) => a.slice(i+1).map(n => e-n)); 
 
console.log(result);

0

我以前Array.prototype.indexOf()來解決我的問題。

var j = boids.indexOf(this); 
//get index of current element i array. 

if (j < boids.length) { 
    // if the index is lower than the overall length of the array (e.g. check traverse the array to elements infront of the current element, ignoring those behind) 

    //Perform calculations here 

    j++; //increment j 

}