Array: ['Date Taken', 'Weight'],
我有这个数组,我迭代它的方式是:
for (vb = 0, len = Array.length; vb < len; vb++) {
alert(Array[vb]); // would give me the Array Values...
}
Obj: {DateTaken: 'this.getPicker()', Weight: 'this.getWeight()'}
DateTaken:'value 1, value 2'
或类似的东西。答案 0 :(得分:1)
好的,那是伪Javascript! :)
这是真正的JS:
var myArray = ['Date Taken', 'Weight'];
for (var i = 0, len = myArray.length; i < len; i++)
{
alert(myArray[i]); // would totally give you myArray Values!
}
var myObj = { DateTaken: this.getPicker(), Weight: this.getWeight() };
要迭代myObj
的键和值,您可以执行以下操作:
for (var i in myObj)
{
alert('the key is ' + i + ' and value is ' + myObj[i]);
}
myObj
中的键可以包含任何内容,所以如果你想在DateTaken中使用多个字符串,那么它将如下所示:
var myObj = { DateTaken: ['aloha', 'mahalo', 'etc'], Weight: this.getWeight() };
答案 1 :(得分:1)
有人可能已经为Object原型添加了自定义键,因此通常最好检查所有键是否都是实际的对象属性。要迭代对象键,您将:
var myObj = { DateTaken: this.getPicker(), Weight: this.getWeight() };
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
alert("Key: " + key + ", value: " + myObj[key]);
}
}
如果您的值可以是数组,则可以将此方法与您已经为阵列找到的方法结合使用。我在这里使用帮助'输出'字符串来组成输出。
var myObj = { single: "foo", multiple: ["one", "two", 3] };
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
var output = "key: " + key + ", value = ";
// Check for Array
if (typeof myObj[key] == "object" && myObj[key].length != undefined) {
output += "[";
for (var i = 0, len = myObj[key].length; i < len; ++i) {
output += myObj[key][i] + ",";
}
output += "]";
} else {
output += myObj[key];
}
alert(output);
}
}