简体   繁体   English

如何在Knockout.JS observableArray上进行每个操作?

[英]How do I for-each over a Knockout.JS observableArray?

All attempts to iterate over a KO observableArray have failed. 遍历KO observableArray的所有尝试均失败。 The flow just jumps over the block like the array is empty. 流就像数组为空一样跳过块。

It's not, because its bound to some HTML and the debugger shows 7 items. 并非如此,因为它绑定到某些HTML,并且调试器显示7个项目。

I've tried a normal for with an indexer, an ECMA-5+ forEach and now KO's own arrayForEach utility. 我已经尝试了正常for与索引,一个ECMA-5 + forEach现在KO自己的arrayForEach效用。

var EditorViewModel = function (firstDayOfWeek) {

    this.firstDayOfWeek = firstDayOfWeek;
    this.days = ko.observableArray([]); // Added in server-side generated view below.

    // Reads the activity data from each day and constructs and uploads models.
    this.save = function () {

        var basket = [];

        // Construct the upload activity models.

        ko.utils.arrayForEach(this.days(), function(d) {

            ... // never falls into this block.

There's nothing much out on the web about this, so I guess its a no-brainer. 网上没有太多有关此的内容,所以我想这很容易。 I'm obviously messing it up somehow, but its eluding me this afternoon. 我显然以某种方式弄乱了它,但是今天下午它使我不知所措。

this.days array looks good to me. this.days数组对我来说看起来不错。

调试器转储显示数组中的7个项目

Thanks, Luke 谢谢,卢克

here days is a observableArray which is nothing but a function , to iterate you need to read the value like days() , this is will give you a javascript array. 这里days是一个observableArray ,它不过是一个函数,要迭代您需要读取days()之类的值,这将为您提供一个javascript数组。

 var days = ko.observableArray([1,3,4,5,6]); days().forEach(function(v,i){ alert(v); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 

我不知道为什么它不能与forEach方法forEach使用,但是我确实使用正确编写for索引迭代器来实现它。

for (dayIndex = 0; dayIndex < this.days().length; dayIndex++) { ... }

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

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