我有后面提到的对象数组,我希望将实际属性“string”存储为变量,并使用javascript将值存储在单独的变量中。这是可能的,如果是这样的话?
states = {
"Alaska": 663267,
"Texas": 268581,
"California": 163696,
"Montana": 147042,
"New Mexico": 121589,
"Arizona": 113998,
"Nevada": 110561
};
答案 0 :(得分:0)
我会尝试以下内容:
// This would be the constructor
// for an object with two values
// One for the city and one for the miles.
function CityMiles(city, miles){
this.city = city;
this.miles = miles;
}
// This is the array, which will hold the CityMiles objects.
var citiesMiles = [];
// Iterate through the keys of states
for(var key in states){
if(states.hasOwnProperty(key)){
// Push in the citiesMiles array a new CityMiles object
// for the current state.
citiesMiles.push(new CityMiles(key, states[key]));
}
}
下面是一个片段,可以看到它的实际效果。
var states = {
"Alaska": 663267,
"Texas": 268581,
"California": 163696,
"Montana": 147042,
"New Mexico": 121589,
"Arizona": 113998,
"Nevada": 110561
};
function CityMiles(city, miles){
this.city = city;
this.miles = miles;
}
var citiesMiles = [];
for(var key in states){
if(states.hasOwnProperty(key)){
citiesMiles.push(new CityMiles(key, states[key]));
}
}
function addRow(city, miles) {
var table = document.getElementById("cityMilesTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= city;
row.insertCell(1).innerHTML= miles;
}
for(var i=0; i<citiesMiles.length; i++){
addRow(citiesMiles[i].city, citiesMiles[i].miles);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table" id="cityMilesTable">
<thead>
<tr>
<th>City</th>
<th>Miles</th>
</tr>
</thead>
<tbody>
</tbody>
</table>