Kra*_*786 26 javascript arrays
我在javascript中经常遇到"Array-Like Object"这个术语.它是什么 ?它和普通阵列有什么区别?什么是类似数组的对象和普通对象之间的区别?
Pau*_* S. 28
它是什么?
一个Object,其长度属性为非负整数,通常还有一些索引属性.例如
var ao1 = {length: 0}, // like []
ao2 = {0: 'foo', 5: 'bar', length: 6}; // like ["foo", undefined × 4, "bar"]
Run Code Online (Sandbox Code Playgroud)
您可以使用将类似Array的对象转换为其Array对象Array.prototype.slice
var arr = Array.prototype.slice.call(ao1); // []
Run Code Online (Sandbox Code Playgroud)
它和普通阵列有什么区别?
它不是由构造Array
或与阵列文字 []
等(通常)将不会从继承Array.prototype
.该长度属性通常不会自动更新两种.
ao1 instanceof Array; // false
ao1[0] = 'foo';
ao1.length; // 0, did not update automatically
Run Code Online (Sandbox Code Playgroud)
什么是类似数组的对象和普通对象之间的区别?
没有区别.即使是正常的数组是对象中的JavaScript
ao1 instanceof Object; // true
[] instanceof Object; // true
Run Code Online (Sandbox Code Playgroud)
著名的HTMLCollection
( documentation ) 和arguments
( documentation ) 是自动创建的类数组对象。
HTMLCollection
真实数组示例之间的一些快速数组(例如)差异:
var realArray = ['value1', 'value2'];
var arrayLike = document.forms;
Run Code Online (Sandbox Code Playgroud)
相似之处:
长度吸气剂是一样的:
arrayLike.length; // returns 2;
realArray.length; // returns 2; //there are 2 forms in the DOM.
Run Code Online (Sandbox Code Playgroud)
索引 getter 是相同的:
arrayLike[0]; // returns an element.
realArray[0]; // returns an element. ('value')
Run Code Online (Sandbox Code Playgroud)
他们都是objects
:
typeof arrayLike; // returns "object"
typeof realArray; // returns "object"
Run Code Online (Sandbox Code Playgroud)
区别:
在阵列状的join()
,concat()
,includes()
等等,方法是不是一个功能:
arrayLike.join(", "); // returns Uncaught TypeError: arrayLike.join is not a function (also relevant to `concat()`, `includes()` etc.)
realArray.join(", "); // returns "value1, value2"
Run Code Online (Sandbox Code Playgroud)
数组 like 并不是真正的数组:
Array.isArray(arrayLike); //returns "false"
Array.isArray(realArray); //returns "true"
Run Code Online (Sandbox Code Playgroud)
在像你不能设置长度属性的数组中:
arrayLike.length = 1;
arrayLike.length; //return 2; //there are 2 forms in the DOM.
realArray.length = 1;
realArray.length; //return 1;
Run Code Online (Sandbox Code Playgroud)