如何迭代具有多个值的数组

How to iterate over array with multiple values

我正在尝试从数组填充 select 框。我需要与文本不同的值。

到目前为止,这段代码正在运行,因为我得到了正确的值:

var myArray = [];
$('#ctl00_ContentPlaceHolderBody_labelTider > div').each(function () {
    myArray.push({
        content: $(this).find('th').text(),
        id: $(this).attr('id')
    });
});
console.log(myArray);

但是,我无法通过 Google 弄清楚或找到如何遍历这些并获取值。

for(arr = 0; arr < myArray.length; arr++) {

    jQuery('<option/>', {
        value: myArray[arr],
        text: myArray[arr]
    }).appendTo('.selectLocation');
}

这导致 [object Object]

任何能够指导我正确方向的人将不胜感激。

问题是因为您将整个对象设置为属性值,而不是该对象的相关属性。试试这个:

for(arr = 0; arr < myArray.length; arr++){
  jQuery('<option/>', {
    value: myArray[arr].content,
    text: myArray[arr].id
  }).appendTo('.selectLocation');
}

请注意,您可以使用 map() 创建一个包含 HTML 字符串的数组,然后 join() 在追加时将它们全部放在一起,从而使代码更加简洁:

var html = $('#ctl00_ContentPlaceHolderBody_labelTider > div').map(function() {
  return `<option value="${this.id}">${$(this).find('th').text()}</option>`;
}).get();
$('.selectLocation').append(html.join(''));

使用 value: myArray[arr].content 价值 和 value: myArray[arr].id 因为你的 myArray 是对象数组。

for(arr = 0; arr < myArray.length; arr++){

        jQuery('<option/>', {
        value: myArray[arr].content,
        text: myArray[arr].id
            }).appendTo('.selectLocation');
    }