简体   繁体   English

为什么对象数组在Firebug中显示空白,尽管其中包含项目-Javascript + AngularJS

[英]Why array of objects is showing blank in firebug though it contain items - Javascript + AngularJS

Following is the screenshot, I am unable to trace what is going wrong here with JavaScript. 以下是屏幕截图,我无法跟踪JavaScript在这里出了什么问题。

If you see that the array in firebug is showing a blank array and if I console the length it is also coming 0 . 如果您看到Firebug中的数组显示一个空白数组,并且如果我控制长度,它也将变为0 BUT if I click the (+) icon its showing the data. 但是,如果我单击(+)图标,它将显示数据。 Let me know what I am doing wrong with the code. 让我知道我在用代码做错什么。

Code - 代码-

            //scope.days is an array of objects
            var newArr = [];
            var myArr = [];
            myArr = scope.days;
            console.log(myArr.length);
            var weekNum = 1;
            newArr['week'+weekNum] = [];
            for(var i=1; i<= myArr.length; i++) {
                newArr['week'+weekNum].push(myArr[i]);
                if(i%7 == 0){
                    weekNum = weekNum + 1;
                    newArr['week'+weekNum] = [];
                }
            }
            scope.days = newArr;

Firebug Screenshot - Firebug屏幕截图-

图片

It's helpful to understand that objects can be accessed using either bracket or dot notation. 理解可以使用括号或点表示法访问对象很有帮助。 Also note that Arrays are also objects . 另请注意, 数组也是对象

So myObj with a property myProp can be accessed using either myObj["myProp"] or myObj.myProp . 所以myObj与属性myProp可使用任一被访问myObj["myProp"]myObj.myProp Square bracket notation is useful when we want to dynamically access a property but we don't know it's identifier at design time. 当我们要动态访问属性但在设计时不知道它的标识符时,方括号表示法很有用。 ie we want to use a dynamically created label: 即我们要使用动态创建的标签:

var label = "myProp";
myObj[label] = "xyz";

So the point of the above is that square bracket notation is a means to reference properties of an object. 因此,以上观点是,方括号表示法是一种引用对象properties的方法。 In your code you do this: 在您的代码中,您可以执行以下操作:

newArr['week'+weekNum] = [];

apparently with the intent of using 'week'+weekNum as an index into the array, but instead what it is actually doing is making a property assignment. 显然,其目的是使用'week'+weekNum作为数组的索引,但是实际上它是在进行属性分配。 So you can continue to make 'week'+weekNum all week long and array length will still be zero because you are not assigning elements to the array but instead generating new properties. 因此,您可以继续将'week'+weekNum整周,并且数组长度仍为零,因为您没有为数组分配元素,而是生成了新的属性。

What you likely want is just 您可能想要的只是

newArr[weekNum] = [];

An Array is indexed from 0 and up. Array的索引从0开始。 Your array contains no items. 您的数组不包含任何项目。 Although it does have properties. 尽管它确实具有属性。

You're using it like an Object . 您像使用Object一样使用它。 If you were to define it as such ( newArr = { } ), Firebug would have a better idea of how to render it. 如果要这样定义它( newArr = { } ),Firebug将对如何呈现它有一个更好的想法。

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

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