Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Фильтрация обьекта по определённому параметру (https://javascript.ru/forum/misc/27703-filtraciya-obekta-po-opredeljonnomu-parametru.html)

konstantinopol 22.04.2012 00:31

Фильтрация обьекта по определённому параметру
 
Доброго времени суток.

Ситуация такая: создаётся обьект. Есть конструктор и всё проходит достаточно хорошо. Проблема в функции для фильтрации в строке 24.


console.log("==Ship Test==");
	var ship = new AIS.Ship(211509880, 50.733173, 7.1108766, 173.4);
	test("Ship does not have correct mmsi", ship.mmsi === 211509880);
	test("Ship does not have correct latitude", ship.latitude === 50.733173);
	test("Ship does not have correct logitude", ship.longitude === 7.1108766);
	test("Ship does not have correct courseOverGround", ship.courseOverGround === 173.4);
	
	console.log("==ShipList Test==");
	test("ShipList missing a 'list' property", typeof(new AIS.ShipList().list) === 'object');
	
	var shipListCreator = function(){
		var shiplist = new AIS.ShipList();
		shiplist.list.push(new AIS.Ship(211509880, 50.733173, 7.1108766, 0));
		shiplist.list.push(new AIS.Ship(211509880, 40.733173, 7.1108766, 173.4));
		shiplist.list.push(new AIS.Ship(211509880, 30.733173, 7.1108766, 200.4));
		return shiplist;
	};
	
	var courseOverGroundFilter = function(ship){ return ship.courseOverGround > 180;};
	var mmsiFilter = function(ship){ return ship.mmsi === 211509881;};
	var latitudeFilter = function(ship){ return ship.latitude > 40;};
	
	var shipList = shipListCreator();
	shipList.filter(courseOverGroundFilter);
	test("Shiplist not correctly filtered on courseOverGround", shipList.list.length === 1);
	
	shipList = shipListCreator();
	shipList.filter(mmsiFilter);
	test("Shiplist not correctly filtered on mmsi", shipList.list.length === 0);
	
	shipList = shipListCreator();
	shipList.filter(latitudeFilter);
	test("Shiplist not correctly filtered on latitude", shipList.list.length === 2);


Я начал её писать, но незнаю как спросить правильный параметр для фильтрации. Чтобы это всё происходило автоматически.

var newlist = [];
		var laenge = this.list.length;
		for(var k=0; k< laenge;k++ )
		{
			if( this.list[k]...   < filterFunction )
                        {
				
			}
		}



Как мне уточнить у атрибута filterFunction кто он(mmsi, latitude, longitude, courseOverGround)?

Зарание благодарен!

konstantinopol 22.04.2012 22:21

Спасибо, разобрался. Функция выглядит вот так:
var newlist = new ShipList();
		var laenge = this.list.length;
		for(var k=0; k< laenge;k++ )
		{
			if(filterFunction.call(this, this.list[k]))
			{
				newlist.list.push(this.list[k]);
			}
		}
		this.list = newlist.list;


Часовой пояс GMT +3, время: 10:45.