Javascript新手..如何将对象属性存储为变量,并将其值存储为另一个变量

Javascript Newbie...How do you store an object property as a variable and its value as another?

本文关键字:变量 存储 另一个 新手 对象 属性 Javascript      更新时间:2023-09-26

我有后面提到的对象数组,我希望将实际属性"string"存储为一个变量,并使用javascript将值存储在一个单独的变量中。这可能吗?如果可能,怎么做?

states = {
    "Alaska": 663267,
    "Texas": 268581,
    "California": 163696,
    "Montana": 147042,
    "New Mexico": 121589,
    "Arizona": 113998,
    "Nevada": 110561
};

我会尝试以下方法:

// 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>