简体   繁体   English

如何获得数组/对象的长度

[英]How to get the length of an array/object

Ok so I have a backbone model that is giving me the following array (or at least what I believe should be an array). 好的,所以我有一个主干模型,该模型为我提供了以下数组(或至少我认为应该为数组的数组)。 Below is a screenshot of the console.log of my array. 下面是我的阵列的console.log的屏幕截图。

在此处输入图片说明

So the array's name is myModel, and the following gives me an undefined value. 因此,数组的名称为myModel,以下内容为我提供了一个未定义的值。

myModel.length

How can I go about getting the length of this array/Object so that I can loop over it? 我该如何获取该数组/对象的长度,以便可以对其进行循环?

What you have there could be an Array-like Object. 您所拥有的可能是一个类似数组的对象。 The easiest thing to do is just to turn it into an Array. 最简单的事情就是将其变成一个数组。 If you can use ES6 then your best option is Array.from(myModel) . 如果可以使用ES6,那么最好的选择是Array.from(myModel)

If you can't use ES6 you can use Array.prototype.slice.call(myModel) . 如果不能使用ES6,则可以使用Array.prototype.slice.call(myModel)

Both of these methods will turn your Array-like Object into an Array! 这两种方法都将把类似数组的对象变成数组! (you do have to store the result in a variable) (您必须将结果存储在变量中)

It looks like you're working with an Object rather than an Array . 看起来您正在使用Object而不是Array In this case, I think your Object has keys 0 - 4, making it look like an array. 在这种情况下,我认为您的对象具有键0-4,使其看起来像一个数组。

You can use the for... in approach to iterate through the Object in the way you would expect. 您可以使用for... in方法以您期望的方式遍历对象。 Of course, you can also use getOwnPropertyNames et al if you're worried about the prototype chain, but your example is fine as it's just a simple object. 当然,如果您担心原型链,也可以使用getOwnPropertyNames等,但是您的示例很好,因为它只是一个简单的对象。

Well obviously that is just an object with array like properties such as; 显然,这只是一个具有数组之类的对象,例如:

var myModel = {0:"this", 1:"that"};

If you do; 如果可以的话;

var myArr = Array.from((myModel.length = Object.keys(myModel).length, myModel));

You will get a proper array like ["this", "that"] . 您将获得一个像["this", "that"]的适当数组。

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

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