我有一系列停车对象, 每个停车场有4层,每层有10个车位
var parking = [
{type:'car',plateNumber:'D555',parkingLevel:L1,parkingNumber:p1},
{type:'car',plateNumber:'M225',parkingLevel:L2,parkingNumber:p9},
{type:'car',plateNumber:'T765',parkingLevel:L2,parkingNumber:p2},
{type:'car',plateNumber:'V366',parkingLevel:L4,parkingNumber:p3},
{type:'car',plateNumber:'D121',parkingLevel:L1,parkingNumber:p5},
{type:'car',plateNumber:'S909',parkingLevel:L3,parkingNumber:p1},
{type:'car',plateNumber:'H551',parkingLevel:L4,parkingNumber:p5},
{type:'car',plateNumber:'S305',parkingLevel:L3,parkingNumber:p1}
]
我想确定当我们将新物品推到停车场阵列时,避免重复停车场 我的意思是我们不能将p1和p1推到L1
这就是我的尝试:
$.each(parking, function (i, item) {
var newCar = {
level: car.parkingLevel,
number: car.parkingNumber
};
var jsonFL = $.map(filterParking, function(v,i) {
return JSON.stringify(v);
});
jsonFL.indexOf( JSON.stringify(newCar) ) > -1 || filterParking.push(newcar);
});
答案 0 :(得分:0)
您可以使用地图。
var map = {}
// when pushing on the array
map[car.plateNumber] = car
// when removing a car
delete map[car.plateNumber]
// check if a car is parked
"undefined" !== typeof map["D555"]
// bonus: you can now get cars by plate number
map["D555"] // {type:'car',plateNumber:'D555',parkingLevel:L1,parkingNumber:p1}
下划线解决方案会增加不必要的依赖性,并且可能会很慢,具体取决于您添加汽车的频率以及阵列增长的大小。
答案 1 :(得分:0)
var parking = [
{type:'car',plateNumber:'D555',parkingLevel:L1,parkingNumber:p1},
{type:'car',plateNumber:'M225',parkingLevel:L2,parkingNumber:p9},
{type:'car',plateNumber:'T765',parkingLevel:L2,parkingNumber:p2},
{type:'car',plateNumber:'V366',parkingLevel:L4,parkingNumber:p3},
{type:'car',plateNumber:'D121',parkingLevel:L1,parkingNumber:p5},
{type:'car',plateNumber:'S909',parkingLevel:L3,parkingNumber:p1},
{type:'car',plateNumber:'H551',parkingLevel:L4,parkingNumber:p5},
{type:'car',plateNumber:'S305',parkingLevel:L3,parkingNumber:p1}
]
var newCar = {
parkingLevel: car.parkingLevel,
parkingNumber: car.parkingNumber
};
for(var i=parking.length-1; i>=0; i--){
if(parking[i].parkingLevel === newCar.parkingLevel && parking[i].parkingNumber === newCar.parkingNumber)
break;
if(i === 0){
parking.push(newCar);
}
}
答案 2 :(得分:0)
Check whether a car is already parked in the given slot before adding to the collection. Assuming newcar
is the new car object you are trying to add, then:
var parkedCars = parking.filter(function(c){ return c.parkingLevel === newcar.parkingLevel && c.parkingNumber === newcar.parkingNumber });
if(parkedCars.length === 0){ //this means there isnt any car parked in that level and slot
parking.push(newcar);
}
答案 3 :(得分:-1)
我使用了underscore.js:
function containsObj(obj, objArray) {
var obj= _.find(objArray, function(val){ return _.isEqual(obj, val);});
return (_.isObject(obj))? true:false;
}
只需包含库文件并使用此功能。