这两者之间有什么区别?
我知道array。size()是一个函数,而数组。长度是一个属性。是否存在使用其中一种而不是另一种的情况?一个更有效率吗?(我想.length会快得多,因为它是一个属性而不是一个方法调用?)为什么人们会选择更慢的选择呢?是否有一些浏览器与其中一种不兼容?
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
实际上,.size()不是纯JavaScript方法,Set对象有一个accessor属性。size有点像.size(),但它不是一个函数方法,就像我说的,它是一个Set对象的accessor属性,以显示Set对象中(唯一的)元素的唯一数量。
size访问器属性返回Set对象中(唯一)元素的数量。
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
length是一个可迭代对象(数组)的属性,返回数组中元素的数量。该值是一个无符号的32位整数,在数值上总是大于数组中最高的索引。
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4
我们可以使用.length属性来设置或返回数组中的元素个数。返回值是一个数字
> set the length: let count = myArray.length;
> return lengthof an array : myArray.length
如果我们需要过滤重复的值并获得集合中元素的计数,我们可以使用.size。
Const set = new set([1,1,2,1]);
console.log (set.size);“