如何在 JavaScript / jQuery 中获取对象的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4079274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:23:29  来源:igfitidea点击:

How to get an object's properties in JavaScript / jQuery?

javascriptjquery

提问by Saiful

In JavaScript / jQuery, if I alertsome object, I get either [object]or [object Object]

在 JavaScript / jQuery 中,如果我alert有一些对象,我会得到[object][object Object]

Is there any way to know:

有什么办法可以知道:

  1. what is the difference between these two objects

  2. what type of Object is this

  3. what all properties does this object contains and values of each property

  1. 这两个对象有什么区别

  2. 这是什么类型的对象

  3. 此对象包含的所有属性以及每个属性的值

?

?

回答by jAndy

You can look up an object's keys and values by either invoking JavaScript's native for inloop:

您可以通过调用 JavaScript 的本机for in循环来查找对象的键和值:

var obj = {
    foo:    'bar',
    base:   'ball'
};

for(var key in obj) {
    alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}

or using jQuery's .each()method:

或使用 jQuery 的.each()方法:

$.each(obj, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

With the exception of six primitive types, everythingin ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toStringmethod on an object, like this:

除了六种基本类型之外,ECMA-/JavaScript 中的所有内容都是对象。数组;职能; 一切都是对象。即使这些原语中的大多数实际上也是具有有限方法选择的对象。当需要时,它们被铸造成引擎盖下的物体。要知道基类名称,您可以调用Object.prototype.toString对象上的方法,如下所示:

alert(Object.prototype.toString.call([]));

The above will output [object Array].

以上将输出[object Array].

There are several other class names, like [object Object], [object Function], [object Date], [object String], [object Number], [object Array], and [object Regex].

还有其他一些类的名称,如[object Object][object Function][object Date][object String][object Number][object Array],和[object Regex]

回答by vol7ron

To get listing of object properties/values:

要获取对象属性/值的列表:

  1. In Firefox - Firebug:

    console.dir(<object>);
    
  2. Standard JS to get object keys borrowed from Slashnick:

       var fGetKeys = function(obj){
          var keys = [];
          for(var key in obj){
             keys.push(key);
          }
          return keys;
       }
    
    // Example to call it:
    
       var arrKeys = fGetKeys(document);
    
       for (var i=0, n=arrKeys.length; i<n; i++){
          console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
       }
    
  1. 在 Firefox - Firebug 中:

    console.dir(<object>);
    
  2. 获取从Slashnick借来的对象键的标准 JS :

       var fGetKeys = function(obj){
          var keys = [];
          for(var key in obj){
             keys.push(key);
          }
          return keys;
       }
    
    // Example to call it:
    
       var arrKeys = fGetKeys(document);
    
       for (var i=0, n=arrKeys.length; i<n; i++){
          console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
       }
    


Edits:

编辑:

  1. <object>in the above is to be replaced with the variable reference to the object.
  2. console.log()is to be used in the console, if you're unsure what that is, you can replace it with an alert()
  1. <object>在上面是要替换为对象的变量引用。
  2. console.log()将在控制台中使用,如果您不确定那是什么,可以将其替换为 alert()

回答by Andy E

i) what is the difference between these two objects

i) 这两个对象有什么区别

The simple answer is that [object]indicates a host object that has no internal class. A host object is an object that is not part of the ECMAScript implementation you're working with, but is provided by the host as an extension. The DOM is a common example of host objects, although in most newer implementations DOM objects inherit from the native Object and have internal class names (such as HTMLElement, Window, etc). IE's proprietary ActiveXObject is another example of a host object.

简单的答案是它[object]表示一个没有内部类的宿主对象。宿主对象是不属于您正在使用的 ECMAScript 实现的一部分,而是由宿主作为扩展提供的对象。DOM 是宿主对象的常见示例,尽管在大多数较新的实现中,DOM 对象继承自本机 Object 并具有内部类名称(例如HTMLElementWindow等)。IE 的专有 ActiveXObject 是宿主对象的另一个示例。

[object]is most commonly seen when alerting DOM objects in Internet Explorer 7 and lower, since they are host objects that have no internal class name.

[object]在 Internet Explorer 7 及更低版本中警告 DOM 对象时最常见,因为它们是没有内部类名的主机对象。

ii) what type of Object is this

ii) 这是什么类型的对象

You can get the "type" (internal class) of object using Object.prototype.toString. The specification requires that it always returns a string in the format [object [[Class]]], where [[Class]]is the internal class name such as Object, Array, Date, RegExp, etc. You can apply this method to any object (including host objects), using

您可以使用Object.prototype.toString. 规范要求它总是以 格式返回一个字符串[object [[Class]]],其中[[Class]]是内部类名,例如ObjectArrayDateRegExp等。您可以将此方法应用于任何对象(包括宿主对象),使用

Object.prototype.toString.apply(obj);

Many isArrayimplementations use this technique to discover whether an object is actually an array (although it's not as robust in IE as it is in other browsers).

许多isArray实现使用这种技术来发现一个对象是否实际上是一个数组(尽管它在 IE 中不如在其他浏览器中那样健壮)。



iii) what all properties does this object contains and values of each property

iii) 该对象包含的所有属性以及每个属性的值

In ECMAScript 3, you can iterate over enumerable properties using a for...inloop. Note that most built-in properties are non-enumerable. The same is true of some host objects. In ECMAScript 5, you can get an array containing the names of all non-inherited properties using Object.getOwnPropertyNames(obj). This array will contain non-enumerable and enumerable property names.

在 ECMAScript 3 中,您可以使用for...in循环遍历可枚举的属性。请注意,大多数内置属性是不可枚举的。某些宿主对象也是如此。在 ECMAScript 5 中,您可以使用Object.getOwnPropertyNames(obj). 此数组将包含不可枚举和可枚举的属性名称。

回答by Halil ?zgür

I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect

我希望这不会被视为垃圾邮件。在无休止的调试会话之后,我谦虚地写了一个函数:http: //github.com/halilim/Javascript-Simple-Object-Inspect

function simpleObjInspect(oObj, key, tabLvl)
{
    key = key || "";
    tabLvl = tabLvl || 1;
    var tabs = "";
    for(var i = 1; i < tabLvl; i++){
        tabs += "\t";
    }
    var keyTypeStr = " (" + typeof key + ")";
    if (tabLvl == 1) {
        keyTypeStr = "(self)";
    }
    var s = tabs + key + keyTypeStr + " : ";
    if (typeof oObj == "object" && oObj !== null) {
        s += typeof oObj + "\n";
        for (var k in oObj) {
            if (oObj.hasOwnProperty(k)) {
                s += simpleObjInspect(oObj[k], k, tabLvl + 1);
            }
        }
    } else {
        s += "" + oObj + " (" + typeof oObj + ") \n";
    }
    return s;
}

Usage

用法

alert(simpleObjInspect(anyObject));

or

或者

console.log(simpleObjInspect(anyObject));

回答by Z. Zlatev

Get FireBugfor Mozilla Firefox.

获取适用于 Mozilla Firefox 的FireBug

use console.log(obj);

console.log(obj);

回答by Paul Irish

Spotlight.jsis a great library for iterating over the window object and other host objects looking for certain things.

Spotlight.js是一个很棒的库,用于遍历 window 对象和其他宿主对象以查找某些内容。

// find all "length" properties
spotlight.byName('length');

// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });

// or all properties with `RegExp` values
spotlight.byKind('RegExp');

// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });

You'll like it for this.

你会喜欢这个的。

回答by J Jesus Loera V

Scanning object for first intance of a determinated prop:

确定道具的第一次扫描对象:

var obj = {a:'Saludos',
            b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
           d:'Hasta luego'
            }
function scan (element,list){
    var res;
    if (typeof(list) != 'undefined'){
        if (typeof(list) == 'object'){
            for(key in list){
               if (typeof(res) == 'undefined'){
                res = (key == element)?list[key]:scan(element,list[key]);
               }
            });
        }
    }
    return res;
}
console.log(scan('a',obj));