我有2个数组:
ids = [a,b,c,d,e,f....];
savedRepods = [e,f];
function getPoints(){
for (var i = 0; i < savedRepods.length; i++) {
if(ids.includes(savedRepods[i]) ) {
console.log(savedRepods[i]);
}
}
}
我知道值在数组中,但这不会向我显示值console.log(savedRepods[i]);
完整代码:
/** get saved values from the server */
var savedRepods = <?php echo json_encode($userPostsInternal); ?> ;
savedRepods = savedRepods.split(",");
/** create single arrays for the values */
var date = [],
coords = [],
ids = [],
metal = [],
plastic = [],
paper = [],
glass = [],
indirizzo = [];
/** convert to a variable ALL the other values form the server */
var array = <?php echo $contents; ?> ;
/** push single values into correspondent arrays */
array.map(function(item) {
coords.push(item.Lat + "," + item.Lng);
ids.push(item.ID);
date.push(item.Date);
plastic.push(item.Plastic);
paper.push(item.Paper);
glass.push(item.Glass);
metal.push(item.Metal);
});
/**
* Now process the response from locationData
*/
var locations = getPoints();
/**
* findLatLang
*/
function findLatLang(location, geocoder, value) {
/**
* Return new Promise what resolves when
* the geocoder is successfull
* and push in the array of promises
*/
return new Promise(function(resolve, reject) {
/** Do geocoder */
geocoder.geocode({
'location': location
}, function(results, status) {
/**
* If geocoder is Ok
*/
if (status === 'OK') {
/**
* When the geocoder is successfull located
* resolve the promise and send the response of formate address
*/
resolve([results[0].formatted_address, value]);
} else {
/**
* Reject the promise
*/
reject(new Error('Couldnt\'t find the location ' + location));
}
})
})
}
/**
* processData
* return an array of promises
*/
function getPoints(){
/**
* Declare a variable of promises that have a geocoder
*/
let locationData = [];
for (var i = 0; i < savedRepods.length; i++) {
if(ids.includes(savedRepods[i]) ) {
console.log(savedRepods[i]);
var geocoder = new google.maps.Geocoder;
var latlngStr = coords[a].split(',', 2);
var latlng = {
lat: parseFloat(latlngStr[0]),
lng: parseFloat(latlngStr[1])
};
/**
* Push geocoder in array of locationdata
* Send the geocoder object on function and send the map
*/
locationData.push(findLatLang(latlng, geocoder, a))
}
}
/** return array of promises */
return locationData;
}
Promise.all(locations)
.then(function(returnVals){
indirizzo = returnVals;
doAddress(indirizzo)
});
var usedId = [],
usedMetal = [],
usedGlass = [],
usedPaper = [],
usedLocation = [],
usedPlastic = [];
const data = [];
function doAddress(indirizzo) {
indirizzo.forEach(function(item){
var a = item[1];
var location = item[0];
let newObj = {};
newObj.idValue = ids[a];
newObj.addressValue = location;
newObj.metalValue = metal[a];
newObj.glassValue = glass[a];
newObj.plasticValue = plastic[a];
newObj.paperValue = paper[a];
data.push(newObj);
$("#eachValue ul").append("<li class='list-group-item'>repod id= " + ids[a] + "<br> Indirizzo = " + location + "<br> Metallo = " + metal[a] + ", <br> Plastica = " + plastic[a] + ", <br> Vetro = " + glass[a] + ", <br> Carta = " + paper[a] + "</li>");
})
const resultMetal = data.sort((a, b) => b.metalValue - a.metalValue)[0];
const resultGlass = data.sort((a, b) => b.glassValue - a.glassValue)[0];
const resultPaper = data.sort((a, b) => b.paperValue - a.paperValue)[0];
const resultPlastic = data.sort((a, b) => b.plasticValue - a.plasticValue)[0];
$("#metal p").html("Il repod con id "+resultMetal.idValue+"<br>situato in <br>" + resultMetal.addressValue + "<br> ha consumato più metallo con un valore di " + resultMetal.metalValue);
$("#vetro p").html("Il repod con id "+resultGlass.idValue+"<br>situato in <br>" + resultGlass.addressValue + "<br> ha consumato più vetro con un valore di " + resultGlass.glassValue);
$("#plastica p").html("Il repod con id "+resultPlastic.idValue+"<br>situato in <br>" + resultPlastic.addressValue + "<br> ha consumato più plastica con un valore di " + resultPlastic.plasticValue);
$("#carta p").html("Il repod con id "+resultPaper.idValue+"<br>situato in <br>" + resultPaper.addressValue + "<br> ha consumato più carta con un valore di " + resultPaper.paperValue);
}
[可能由于数组条目是object
类型。 Array.prototype.contains
不适用于对象类型。因为在js中:
var a = {
prop: 'value'
}
var b = {
prop: 'value'
}
if (a != b) {
console.log('a is not equal to b');
}
在javascript中=
(等于)的运算符检查对于object
类型,引用是否相同。引用是对象在内存中的地址。在我的第一个示例中,a
和b
有其自己的不同引用,因此对于javascript a
不等于b
。
代替contains
,您可以使用some
方法,该方法需要回调来手动检查匹配项。这是一个使用some
方法查找元素是否存在的示例。
var array = [
{ name: 'Anna', age: 19 },
{ name: 'Sara', age: 17 },
{ name: 'John', age: 21 },
{ name: 'Doe', age: 34 }
]
var john = { name: 'John', age: 21 };
if (array.some((other) => {
return other.name == john.name && other.age == john.age
})) {
console.log('John is exists in the array');
}
如果您不想检查每个属性的对象,可以检查JSON.stringfy(other) == JSON.stringfy(john)
。