Array.size() vs Array.length

后端 未结 10 805
一个人的身影
一个人的身影 2020-11-28 01:17

What is the difference between the two?

So I know that array.size() is a function while array.length is a property. Is there a usecase for

相关标签:
10条回答
  • 2020-11-28 01:58

    The property 'length' returns the (last_key + 1) for arrays with numeric keys:

    var  nums  =  new  Array ();
    nums [ 10 ]  =  10 ; 
    nums [ 11 ]  =  11 ;
    log.info( nums.length );
    

    will print 12!

    This will work:

    var  nums  =  new  Array ();
    nums [ 10 ]  =  10 ; 
    nums [ 11 ]  =  11 ;
    nums [ 12 ]  =  12 ;
    log.info( nums.length + '  /  '+ Object.keys(nums).length );
    
    0 讨论(0)
  • 2020-11-28 02:08

    Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.

    The size accessor property returns the number of (unique) elements in a Set object.

    const set1 = new Set();
    const object1 = new Object();
    
    set1.add(42);
    set1.add('forty two');
    set1.add('forty two');
    set1.add(object1);
    
    console.log(set1.size);
    // expected output: 3
    

    And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

    const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
    
    console.log(clothing.length);
    // expected output: 4
    
    0 讨论(0)
  • 2020-11-28 02:08

    we can you use .length property to set or returns number of elements in an array. return value is a number

    > set the length: let count = myArray.length;
    > return lengthof an array : myArray.length
    

    we can you .size in case we need to filter duplicate values and get the count of elements in a set.

    const set = new set([1,1,2,1]); 
     console.log(set.size) ;`
    
    0 讨论(0)
  • 2020-11-28 02:10

    .size() is not a native JS function of Array (at least not in any browser that I know of).

    .length should be used.


    If

    .size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.

    or

    There might be some plugin on your browser that is mucking with the Array prototype.

    0 讨论(0)
提交回复
热议问题