我写了一个简单的函数来通过 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));
});
当我向第二个数组添加更多值并尝试循环遍历数组以应用函数时,就会出现问题。
$(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 两次