【问题标题】:Javascript Newbie...How do you store an object property as a variable and its value as another?Javascript新手...如何将对象属性存储为变量并将其值存储为另一个?
【发布时间】:2015-02-07 23:18:14
【问题描述】:

我有后面提到的对象数组,我很想将实际属性“字符串”存储为一个变量,并使用 javascript 将值存储在一个单独的变量中。这可能吗?如果可以,怎么办?

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

【问题讨论】:

  • 您能否指定给定上述输入的预期输出?谢谢
  • 你想用这个来完成什么?
  • 那么你将只有一堆变量而不是对象形式的集合,这是你想要的吗?
  • 这个“对象数组”在哪里?

标签: javascript variables object properties


【解决方案1】:

我会尝试以下方法:

// 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]));
    } 
}

下面是一个 sn-p 来查看它的运行情况。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2021-07-21
    • 2011-08-30
    • 2014-10-08
    • 1970-01-01
    相关资源
    最近更新 更多