使用循环访问javascript对象属性

时间:2017-04-04 14:45:33

标签: javascript loops object

如何使用obj循环访问对象for属性?

示例:

var obj = {
        id: 1,
        description: "This space is for description",
        severity: "This is severity",
        assignedTo: "Name of the assigned person",
        status: "Issue Status "
    }

注意:我在谈论这种循环for (var i =0;i <= obj.length;i++),而不是for ... in循环。我想使用document.write()显示它。请,没有jquery,只有javascript。

1 个答案:

答案 0 :(得分:2)

您可以将for循环与Object.keys()一起使用。

注意:提到 squint 时,它不能保证正确的顺序。

var obj = {
  id: 1,
  description: "This space is for description",
  severity: "This is severity",
  assignedTo: "Name of the assigned person",
  status: "Issue Status "
}, elems = Object.keys(obj);

for (var i = 0; i < elems.length; i++) {
  document.write(`Key: ${elems[i]}, Value: ${obj[elems[i]]}<br>`);
}