JSON配列値を介して数学を適用する簡単な関数を書きましたが、問題なく動作します。
$(document).ready(function(){
var arr1 = {"gold":"1000","iron":"2000","wood":"4500","food":"800"} ;
var arr2 = [{"gold":"100","iron":"80","wood":"120","food":"70"}];
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Array.min = function( array ){
return Math.min.apply( Math, array );
};
function getValidenum(resources,cost) {
var output = [] ;
$.each(cost, function(i, item) {
output.push(Math.floor(resources.gold / item.gold)) ;
output.push(Math.floor(resources.iron / item.iron)) ;
output.push(Math.floor(resources.wood / item.wood)) ;
output.push(Math.floor(resources.food / item.food)) ;
});
return Array.min(output) ;
}
alert(getValidenum(arr1,arr2));
});
2 番目の配列にさらに値を追加し、配列をループして関数を適用しようとすると、問題が発生します。
$(document).ready(function(){
var arr1 = {"gold":"1000","iron":"2000","wood":"4500","food":"800"} ;
var arr2 = [{"gold":"100","iron":"80","wood":"120","food":"70"},{"gold":"10","iron":"20","wood":"50","food":"30"}];
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Array.min = function( array ){
return Math.min.apply( Math, array );
};
function getValidenum(resources,cost) {
var output = [] ;
$.each(cost, function(i, item) {
output.push(Math.floor(resources.gold / item.gold)) ;
output.push(Math.floor(resources.iron / item.iron)) ;
output.push(Math.floor(resources.wood / item.wood)) ;
output.push(Math.floor(resources.food / item.food)) ;
});
return Array.min(output) ;
}
$.each(arr2, function(i, item) {
alert(getValidenum(arr1,item));
});
});
arr2 の 2 つの配列の結果を 2 回表示する代わりに
var arr2 = [{"gold":"100","iron":"80","wood":"120","food":"70"},{"gold":"10","iron":"20","wood":"50","food":"30"}];
NaNが2回表示されます