【问题标题】:JavaScript : Get values of attributes of an objectJavaScript:获取对象属性的值
【发布时间】:2018-06-29 09:38:36
【问题描述】:

我正在尝试获取对象所有属性的值,我尝试使用Object.values(),我只在控制台中使用这个:

var a = queryPlan.combo.getFilterMapOfIdToWgt(); console.log(Object.values(a));

[constructor]

但它实际上包含很多值:

[constructor]
0:constructor
activeErrorsTpl:(8) ["<tpl if="errors && errors.length">", "<ul class="{listCls}">", "<tpl if="Ext.enableAria">", "<tpl if="fieldLabel"><div>{fieldLabel}</div></tpl>", "</tpl>", "<tpl for="errors"><li>{.}</li></tpl>", "</ul>", "</tpl>"]
activeUI:"default"
autoGenId:true
auxStore:constructor {removed: Array(0), blockLoadCounter: 0, isInitializing: false, initConfig: ƒ, initialConfig: {…}, …}
bindings:[]
bodyEl:constructor {dom: div#hemonth-1050-bodyEl.x-form-item-body.x-form-item-body-default.x-form-text-field-body.x-form-text…, id: "hemonth-1050-bodyEl", el: constructor, initConfig: ƒ, initialConfig: {…}, …}

我正在尝试访问每个值。是否有可能得到它,如果是,我如何得到它? 非常感谢您的帮助和提前感谢。

【问题讨论】:

  • 请输入示例
  • 应该如何帮助您解决您提出这个问题的方式。

标签: javascript javascript-objects


【解决方案1】:

ES6+

如果你使用 ES6+,你可以使用 for..of 循环:

var myArray = [ 1, 2, 3 ];

for (var v of myArray) {
   console.log( v );
}
// 1
// 2
// 3

for..of 循环直接迭代对象属性的值。

PRE-ES6

对于 ES6 之前的版本,您可以使用标准的 for 循环:

var myArray = [1, 2, 3];

for (var i = 0; i < myArray.length; i++) {
    console.log( myArray[i] );
}
// 1 2 3

【讨论】:

  • for .. of 用于数组。对于对象,请使用for .. in
  • 你是对的,但for..of 也适用于具有自定义迭代器的对象。
【解决方案2】:

let obj = {
  key1: 'val1',
  print: (x) => { console.log(x)}
}

for(var attr in obj){
  
	if(typeof obj[attr] == 'function'){
  	obj[attr]('123');
  }
  
  if(typeof obj[attr] == 'string'){
  	console.log('hi attr is:',attr, 'with value:',obj[attr])
  }
}

如果不分享对象的外观,我将在这里创建示例对象以及如何循环遍历属性并使用它们。如果您希望对您的问题有更具体的答案,请将其包含在您的问题中

【讨论】:

    猜你喜欢
    • 2016-11-08
    • 2012-09-15
    • 2022-11-18
    • 1970-01-01
    • 2016-09-27
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多