我遇到的问题是我要解决的问题。
我已经设定了一项任务,其中大多数都会执行以下操作;
1)在数组中的每个数字上,打印出(在无序列表中)每个数字的数组值及其相关描述。
代码是执行此任务,如下所示;
var numbers = [
'1',
'2',
'3',
'4',
'5',
'6'
],
description = {
'One': 'Number one',
'Two': 'Number two',
'Three': 'Number three',
'Four': 'Number four',
'Five': 'Number five',
'Six': 'Number six'
};
有没有人知道如何使用某种循环来解决这个问题?
如果你还可以在评论中向我解释,告诉我发生的事情会很棒。
亲切的问候,
乙
答案 0 :(得分:0)
for(var prop in description) {
alert(prop+"::"+description[prop]);
}
这将帮助您迭代描述对象。您可以修改它以匹配数组值。
答案 1 :(得分:0)
您可以指定一个对象数组,每个对象包含一个与该对象的索引值对应的描述:
// assign an array of objects
// numbers[3] for example contains {name: 'Three', description: 'Number three'}
var numbers = [
{name: 'Zero', description: 'Zip!'},
{name: 'One', description: 'Number one'},
{name: 'Two', description: 'Number two'},
{name: 'Three', description: 'Number three'},
{name: 'Four', description: 'Number four'},
{name: 'Five', description: 'Number five'},
{name: 'Six', description: 'Number six'}
],
// a results container
result = [];
// iterate through the numbers array and push a string
// string containing index, name and description to
// result
for (var i=0;i<numbers.length,i=i+1){
result.push(i+': name = '+numbers[i].name+
', description = '+numbers[i].description);
}
// show the result, joining the result array into a string,
// separated by a line break '\n'
alert(result.join('\n'));
/* alerts:
0: name = Zero, description = Zip!
1: name = One, description = Number one
2: name = Two, description = Number two
3: name = Three, description = Number three
4: name = Four, description = Number four
5: name = Five, description = Number five
6: name = Six, description = Number six
*/