Javascript新手..如何将对象属性存储为变量,并将其值存储为另一个变量
Javascript Newbie...How do you store an object property as a variable and its value as another?
我有后面提到的对象数组,我希望将实际属性"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>
相关文章:
- 当我按下getroute按钮时,我希望我的javascript变量存储在数据库中
- Javascript全局变量存储在哪个对象中
- 将javascript变量存储到HTML文本框中
- 如何将angular.js模型变量存储在javascript变量中
- 如何使用 AngularJS 将变量存储在数组中
- 简单的事情,如何将变量存储到数组中
- 将变量存储到数组 JavaScript 中
- 全局变量存储在 Node.JS 中的什么位置?节点中是否有类似窗口的对象
- 将变量存储到我的服务器
- Selenium IDE - 我可以将Selenium变量存储到javascript变量中吗?
- 如何将这三个变量存储到本地存储中
- 有没有办法将会话变量存储在 AJAX 调用的 javascript 中或仅存储在方法中
- 如何将javascript变量存储到php中
- mootools将变量存储在IE中iframe的父级中
- 将包含数据的变量存储到Mysql中
- 变量存储函数作为基元类型或引用类型
- 将javascript变量存储在mysql数据库中
- 对于Loop/Each Loop变量存储和比较(jQuery或Javascript
- 如何使用AJAX将javascript变量存储到我的sql数据库中
- 将javascript变量存储在数据属性中并进行检索