Why do JavaScript arguments have a length property and other objects don't?

Why does the code below have a property length(in particular, an object created by passing arguments to a function):

function somefunction() {
  var a = arguments;
  return a;
}

var b = somefunction('a','b','c')

b
  {'0': 'a', '1': 'b', '2': 'c'}
  b.length
  3

While if a normal object is created, it has no property length:

var someobj = {
  '0': 'abc',
  '1': 'def',
  '2': 'efg'
}

someobj.length
   undefined

+4
source share
2 answers

var myObject = {a: "x", length: 5} .length. arguments.length. , , non-enumerable, - console.log, . :

var someobj = Object.defineProperty({
    '0': 'abc',
    '1': 'def',
    '2': 'efg',
    'length': 'whatever'
}, 'length', {enumerable:false});
console.log(someobj); // {0: "abc", 1: "def", 2: "efg"}
console.log(someobj.length); // whatever
+2

, arguments, , Array, arguments.length, , , *. Function.length, .

function myFunc(param) {
        return arguments.length;
}

myFunc('param1', 'param2'); // 2

myFunc.length; // 1

* Javascript . , arguments.

( ), Object.keys:

let myObj = {
     a: "one",
     b: "two"
};

Object.keys(myObj).length; // 2
+1

Source: https://habr.com/ru/post/1674217/


All Articles