想象一下,我有一个包含一组公共变量和私有变量的对象
function myObj()
{
var private1 = 1;
var private2 = 2;
this.func = function(){console.log('anything');};
this.public1 = 3;
this.public2 = '4';
}
有没有办法创建一个可以解析对象并检索公共变量的名称,值和类型的函数。
这个函数的原型是:
parseObj(object)
控制台结果将是:
>object has public1 with value 3 of type Number
>object has public2 with value 4 of type String
答案 0 :(得分:2)
试试这个:
Object.entries(object).forEach((prop) => {
const [name, value] = prop;
console.log(`object has ${name} with value of ${value} and type ${typeof(value)}`)
})
我在控制台中得到了这个:
// object has func with value of function (){console.log('anything');} and type function
// object has public1 with value of 3 and type number
// object has public2 with value of 4 and type string
答案 1 :(得分:2)
您可以使用 for in循环:
轻松制作此类功能function parseObj(object) {
for(var name in object) {
if(object.hasOwnProperty(name)) {
// ignoring methods
if(typeof object[name] !== 'function') {
console.log('object has '+name+' with value '+object[name]+' of type '+typeof object[name]);
}
}
}
}
答案 2 :(得分:1)
您未在OP中包含“非ECMAScript 2015”条件。如果ECMAScript 5.1正常,那么 Object.keys 将返回自己的属性(有一个polyfill on MDN)。
没有内置函数可以准确地返回值的类型(尽管您可以相当容易地自己完成)。 typeof 会返回有用但与类型不匹配的值,例如没有“功能”类型,但是:
typeof function(){}
返回“功能”。此外,主机对象可能返回各种值(例如“未知”)。
function myObj()
{
var private1 = 1;
var private2 = 2;
this.func = function(){console.log('anything');};
this.public1 = 3;
this.public2 = '4';
}
var obj = new myObj();
function showProps(obj) {
Object.keys(obj).forEach(function(key) {
console.log('object has ' + key + ' with value ' + obj[key] +
' with typeof ' + (typeof obj[key]));
});
}
showProps(obj);