我有一个数组,其中包含有关状态特征的各种信息,需要通过几种方式对其进行修改。首先,如果区域相同,我需要按区域排序,然后按名称排序。所以我使用parseInt获取实际的int而不是字符串,但现在我输了。我如何实现这一目标?我还需要找到填充最多/填充最少的状态并将其存储在变量中。
(function() {
'use strict';
var states = [{
"name": "Alaska",
"area": "663,268 sq mi",
"population": 735132
}, {
"name": "California",
"area": "163,696 sq mi",
"population": 38332521
}, {
"name": "oregon",
"area": "98,381 sq mi",
"population": 3899353
}, {
"name": "washington",
"area": "71,300 sq mi",
"population": 6971406
}];
var moddedStates = {};
for (var i = 0; i < states.length; i++) {
var area = parseInt(states[i].area);
}
}());
答案 0 :(得分:0)
我相信这段代码会做你想要的一切。请注意使用replace
来说明逗号,并使用parseFloat
代替parseInt
,以防某些尺寸包含小数点右边的数字。 (在比较美国各州的规模时可能不是问题,但仍然是进入的良好习惯......)
(function() {
'use strict';
var states = [{
"name": "Alaska",
"area": "663,268 sq mi",
"population": 735132
}, {
"name": "California",
"area": "163,696 sq mi",
"population": 38332521
}, {
"name": "oregon",
"area": "98,381 sq mi",
"population": 3899353
}, {
"name": "washington",
"area": "71,300 sq mi",
"population": 6971406
}];
var mostPopulated = null;
var leastPopulated = null;
states.sort(function (a, b) {
var aArea = parseFloat(a.area.replace(/,/g, ''));
var bArea = parseFloat(b.area.replace(/,/g, ''));
if (aArea < bArea) return -1;
else if (bArea < aArea) return 1;
else if (a.name < b.name) return -1;
else if (b.name < a.name) return 1;
else return 0;
});
for (var i = 0, len = states.length; i < len; i++) {
if (!mostPopulated || states[i].population > mostPopulated.population) {
mostPopulated = states[i];
}
if (!leastPopulated || states[i].population < leastPopulated.population) {
leastPopulated = states[i];
}
}
console.log(states);
console.log(mostPopulated);
console.log(leastPopulated);
}());