Array.size() 与 Array.length [英] Array.size() vs Array.length

查看:40
本文介绍了Array.size() 与 Array.length的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者有什么区别?

所以我知道 array.size() 是一个函数,而 array.length 是一个属性.是否有使用一个而不是另一个的用例?一个更有效率吗?(我认为 .length 会明显更快,因为它是一个属性而不是方法调用?)为什么要使用较慢的选项?是否有一些浏览器与其中一种不兼容?

So I know that array.size() is a function while array.length is a property. Is there a usecase for using one over the other? Is one more efficient? (I would imagine .length to be significantly faster as it is a property rather then a method call?) Why would one ever use the slower option? Are there some browsers that are incompatible with one or the other?

  var x = [];
  console.log(x.size());
  console.log(x.length);
  console.log(x.size()==x.length);
  x =[1,2,3];
  console.log(x.size());
  console.log(x.length);
  console.log(x.size()==x.length);

将打印:

  0, 0, true
  3, 3, true

推荐答案

Array.size() is not a valid method

始终使用长度属性

有一个库或脚本将 size 方法添加到数组原型中,因为这不是本机数组方法.这样做通常是为了添加对自定义 getter 的支持.使用它的一个例子是,当您想获取数组在内存中的大小时(这是我能想到的唯一对这个名称有用的东西).

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 不幸地定义了一个 size 方法,它实际上返回一个对象或数组的长度.不幸的是,函数的长度属性被定义为函数声明它们必须使用替代方法的命名参数的数量,因此选择了大小(计数会是更好的选择).

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).

这篇关于Array.size() 与 Array.length的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆