Array.size() vs Array.length

后端 未结 10 804
一个人的身影
一个人的身影 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:43

    Array.size() is not a valid method

    Always use the length property

    There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).

    Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).

    0 讨论(0)
  • 2020-11-28 01:47

    .size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.

    If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.

    0 讨论(0)
  • 2020-11-28 01:55

    array.length isn't necessarily the number of items in the array:

    var a = ['car1', 'car2', 'car3'];
    a[100] = 'car100';
    a.length; // 101
    

    The length of the array is one more than the highest index.

    As stated before Array.size() is not a valid method.

    More information

    0 讨论(0)
  • 2020-11-28 01:55

    The .size() method is deprecated as of jQuery 1.8. Use the .length property instead

    See: https://api.jquery.com/size/

    0 讨论(0)
  • 2020-11-28 01:56

    Size detects duplicates, it will return the number of unique values

    const set1 = new Set([1, 2, 3, 4, 5, 5, 5, 6]);
    console.log(set1.size);
    // expected output: 6
    
    0 讨论(0)
  • 2020-11-28 01:57

    The .size() function is available in Jquery and many other libraries.

    The .length property works only when the index is an integer.

    The length property will work with this type of array:

    var nums = new Array();
    nums[0] = 1; 
    nums[1] = 2;
    print(nums.length); // displays 2
    

    The length property won't work with this type of array:

    var pbook = new Array(); 
    pbook["David"] = 1; 
    pbook["Jennifer"] = 2;
    print(pbook.length); // displays 0
    

    So in your case you should be using the .length property.

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