我如何在不使用计算的可观察对象的情况下将可观察数组上的 Knockout foreach 一次限制为 5?

How can i limit a Knockout foreach on an observable array to 5 at a time without using computed observables?

我有一个可观察数组,我想用它来填充 table,但我只希望列表中的前 5 个在任何给定时刻显示在 table 上。当我尝试使用 computed observable 时,它​​会使代码变长,我想在保持代码整洁和简单的同时实现这一目标。

    <table>
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <tr>
                <td data-bind="text: firstName"></td>
                <td data-bind="text: lastName"></td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        ko.applyBindings({
            people: [
                { firstName: 'Bert', lastName: 'Bertington' },
                { firstName: 'Charles', lastName: 'Charlesforth' },
                { firstName: 'Author', lastName: 'Dentiste' },
                { firstName: 'James', lastName: 'Depth' },
                { firstName: 'Arnold', lastName: 'Carol' },
                { firstName: 'Ritchie', lastName: 'Dentiste' },
                { firstName: 'Denise', lastName: 'Lemel' }
            ]
        });
    </script>

在 HTML 中使用虚拟 if 绑定怎么样?不是最高效的,但它只有 1 行代码。

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <!-- ko if: ($index() < 5) -->
            <tr>
                <td data-bind="text: firstName"></td>
                <td data-bind="text: lastName"></td>
            </tr>
            <!-- /ko -->
        </tbody>
    </table>

    <button data-bind="click: killBert">Kill Bert</button>
    <script type="text/javascript">
        var viewmodel = {
            people: ko.observableArray([
                { firstName: 'Bert', lastName: 'Bertington' },
                { firstName: 'Charles', lastName: 'Charlesforth' },
                { firstName: 'Author', lastName: 'Dentiste' },
                { firstName: 'James', lastName: 'Depth' },
                { firstName: 'Arnold', lastName: 'Carol' },
                { firstName: 'Ritchie', lastName: 'Dentiste' },
                { firstName: 'Denise', lastName: 'Lemel' }
            ])
        };
        viewmodel.killBert = function (){
          viewmodel.people.remove(function(person){
            return person.firstName === 'Bert';
          });
        };
        ko.applyBindings(viewmodel);
        
    </script>