简体   繁体   English

具有数组原型的javascript对象

[英]javascript object with array prototype

Recently, I read an article that have the following lines 最近,我阅读了一篇包含以下内容的文章

var obj = {};
Array.prototype.push.call(obj, 'aaa', 'bbb', 'ccc');
console.log(obj);
{0: "aaa", 1: "bbb", 2: "ccc", length: 3}

I know it tries to use obj as the context and passing the rest as the arguments. 我知道它尝试使用obj作为上下文,并将其余的作为参数传递。 Before, I only used to push each item into an array. 在此之前,我只用于将每个项目压入数组。 I am curious what is the logic behind this implementation. 我很好奇此实现背后的逻辑是什么。 How it set index as each key of the value and why 'length' is automatically add to the object as well? 如何将index设置为值的每个键,以及为什么还会将'length'自动添加到对象? thanks 谢谢

Because that's how push works . 因为这就是push方式 Most array methods are intentionally generic so they can be applied to other objects, not only arrays. 大多数数组方法是有意通用的,因此它们可以应用于其他对象,而不仅是数组。

When the push method is called with zero or more arguments item1,item2, etc., the following steps are taken: 当使用零个或多个参数item1,item2等调用push方法时,将执行以下步骤:

  1. Let O be the result of calling ToObject passing the this value as the argument. O为调用ToObject并将this值作为参数传递的结果。

This just ensures that this is an object: var O = Object(this); 这只是确保this是一个对象: var O = Object(this);

  1. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length". lenVal为使用参数“ length”调用O的[[Get]]内部方法的结果。

var lenVal = O.length; . lenVal will be undefined in our case, since the object doesn't have a length property. 在本例中, lenVal将是undefined ,因为该对象没有length属性。

  1. Let n be ToUint32 ( lenVal ). nToUint32lenVal )。

Converts lenVal to a number and assigns the result to n . lenVal转换为数字并将结果分配给n undefined will be converted to 0 . undefined将转换为0

  1. Let items be an internal List whose elements are, in left to right order, the arguments that were passed to this function invocation. item为内部List,其元素按从左到右的顺序是传递给此函数调用的参数。

Basically var items = arguments; 基本上var items = arguments; .

  1. Repeat, while items is not empty 重复,但项目不为空
    • Remove the first element from items and let E be the value of the element. 项目中删除第一个元素,并让E为元素的值。
    • Call the [[Put]] internal method of O with arguments ToString ( n ), E , and true . 使用参数ToStringn ), Etrue调用O的[[Put]]内部方法。
    • Increase n by 1. n增加1。

This simply iterates over all entries in items , assigns O[String(n)] = E; 这将简单地遍历items所有条目,分配O[String(n)] = E; and n += 1 . n += 1 This is where each argument you pass to push is assigned to the object! 这是您传递给push的每个参数都分配给该对象的地方!

  1. Call the [[Put]] internal method of O with arguments "length", n , and true . 用参数“ length”, ntrue调用O的[[Put]]内部方法。

Sets length to n : O.length = n; length设置为nO.length = n; . This is where length is set! 这是设置length地方!

  1. Return n . 返回n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM