How does a jQuery instance appear as an array when called in console.log?

后端 未结 5 1876
一个人的身影
一个人的身影 2021-01-03 15:58

When entered into a JavaScript console, a jQuery object appears as an array. However, it\'s still an instance of the jQuery object.

var j = jQuery();
=> [         


        
相关标签:
5条回答
  • 2021-01-03 16:03

    When you call jQuery() you aren't passing any arguments to the function so it is returning an empty object. WHen you pass a selector as argument it creates an object of the elements that match the selector

    0 讨论(0)
  • 2021-01-03 16:05

    I believe they have something like that:

    // Adding items to an object like an Array:
    var myObject = {splice : Array.prototype.splice};
    
    Array.prototype.push.call(myObject, 1, 10, "foo");
    
    // Getting items from an object like an Array:
    
    alert(Array.prototype.slice.call(myObject, 0));
    
    console.log(myObject);
    
    alert(myObject);
    
    0 讨论(0)
  • 2021-01-03 16:06

    The console makes it look like an array because it has array-like properties. It has length and n keys using integers.

    0 讨论(0)
  • 2021-01-03 16:18

    It returns an empty array, because it did nothing - array of elements affected.

    Proper way to inspect would be

    console.log(jQuery);
    

    if you would do

    console.log(jQuery('div'));
    

    you will see that it returns array of elements.

    0 讨论(0)
  • 2021-01-03 16:21

    I think what you're trying to see are your object's properties. If that's the case, you're inadvertently converting the object into a string when you append it to another string. Use the , operator instead of + to show the object properties instead of the "stringified" version of the object:

    console.log('test with string concat: ', j);
    
    0 讨论(0)
提交回复
热议问题