简体   繁体   English

Javascript稀疏数组兼容性

[英]Javascript sparse array compatability

I'm in a situation where I'd like to add to the beginning of an array (instead of using .push() and adding to the end). 我要添加到数组的开头(而不是使用.push()并添加到结尾)。

From what I can gather, using the .unshift() method is potentially not going to work in IE 8? 据我所知,使用.unshift()方法可能无法在IE 8中正常工作?

So I figured "that's ok.. I'll just asign values starting at the end of the array and working my way down"... but I'm wondering if that's ok in every browser? 所以我想“没关系。我只是将值从数组的末尾开始分配,然后一直往下移动”……但是我想知道是否在每个浏览器中都可以吗?

Is it ok do this in all browsers?: 在所有浏览器中都可以吗?:

arr =[];
arr[2] = 'greg';

in chrome console that gives me an array of: 在chrome控制台中,它为我提供了一系列:

[undefined, undefined, 'greg']

Something about that just seems like it wouldn't work somewhere... 关于它的某事似乎在某处不起作用...

You get a sparsed array, which is iterable with the methods of Array, like Array#forEach 您将获得一个稀疏的数组,该数组可以通过Array的方法进行迭代,例如Array#forEach

forEach() executes the provided callback once for each element present in the array in ascending order. forEach()对数组中存在的每个元素以升序执行一次提供的回调。 It is not invoked for index properties that have been deleted or are uninitialized (ie on sparse arrays). 对于已删除或未初始化(即在稀疏数组上)的索引属性,不会调用它。

Caveat : The length property does not reflect the real count of items in the array. 警告length属性不能反映数组中项目的实际数量。 It is build upon the greatest index if the array. 它建立在最大索引(如果数组)的基础上。

The length property represents an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. length属性表示一个无符号的32位整数,该整数在数值上始终大于数组中的最高索引。

I suggest to have a look at this part Relationship between length and numerical properties as well for understanding arrays and the use of length and sparsed parts. 我建议看一下这部分,以了解长度和数值属性之间的关系,以了解数组以及长度和稀疏部分的用法。

 var arr =[]; arr[2] = 'greg'; console.log(arr.length); // 3 arr.forEach(function (a, i) { console.log(i, a); // 2 greg }); 

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

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