Javascript 访问可观察对象数组中的对象字段。淘汰赛

Javascript 访问可观察对象数组中的对象字段。淘汰赛,javascript,knockout.js,ko.observablearray,Javascript,Knockout.js,Ko.observablearray,我有一个表,它是通过数据绑定填充的,数据来自可观察的对象(人)数组。当我点击表格的某个单元格时,一行的索引和一个单元格的索引被写入变量“self.currentLine”和“self.currentCell”,而输入则以100%的宽度和100%的高度显示在上面,覆盖了数据本身。 是否有可能访问可观察数组中特定对象的特定字段,只使用字段索引而不使用字段名?(例如,不是self.persons[0]'name',而是self.persons[0][0]) 下面是一个代码(JS): 以及我使用的HTM

我有一个表,它是通过数据绑定填充的,数据来自可观察的对象(人)数组。当我点击表格的某个单元格时,一行的索引和一个单元格的索引被写入变量“self.currentLine”和“self.currentCell”,而输入则以100%的宽度和100%的高度显示在上面,覆盖了数据本身。 是否有可能访问可观察数组中特定对象的特定字段,只使用字段索引而不使用字段名?(例如,不是self.persons[0]'name',而是self.persons[0][0])

下面是一个代码(JS):

以及我使用的HTML代码:

<table>
        <thead data-bind="template: { name: 'tableHeader', data: columnNames }" />
        <tbody data-bind="template: { name: 'tableContent', foreach: persons }" />
    </table>

    <script id="tableHeader" type="text/html">
        <tr data-bind="foreach: $data">
                <td data-bind="text: $data,
                               css: { 'active': $root.currentItem() == $data }">
                </td>
        </tr>
    </script>

    <script id="tableContent" type="text/html">
        <tr data-bind="click: $root.setLine.bind($data, $index())">
            <td data-bind="click: $root.setCell.bind($data, $element.cellIndex)">
                <span data-bind="text: name"></span>
                <input type="text" data-bind="visible: $root.currentCell() == 0 && $index() == $root.currentLine(),
                                              value: name"/> <!--fixed-->
            </td>
        </tr>
    </script>

在html中,我根据表中单击的单元格设置输入可见。所以现在我需要把一个单元格的值传递给一个输入,这样我就可以编辑这个数据了


更新:像往常一样,我忘记在输入中的value:name()后面加上圆括号“()”。但第二个问题来了。正如我所知,当输入失去焦点时,值必须自动改变。但是我的不会改变…

使用输入
绑定来传递单元格的值:

好的,没有办法访问具有假定索引的字段,要在ObservalArray中从对象读取字段,您可以使用以下语法:
persons()[index].fieldName()
,假设该字段也是可观察的


希望有帮助。

好的,但是如果我不知道字段的名称?有没有可能通过索引或类似的方式获取它的名称?找到了答案,使用Object.keys(persons()[index]),我得到了一个键数组,所以现在我可以获取所需的字段名。
<table>
        <thead data-bind="template: { name: 'tableHeader', data: columnNames }" />
        <tbody data-bind="template: { name: 'tableContent', foreach: persons }" />
    </table>

    <script id="tableHeader" type="text/html">
        <tr data-bind="foreach: $data">
                <td data-bind="text: $data,
                               css: { 'active': $root.currentItem() == $data }">
                </td>
        </tr>
    </script>

    <script id="tableContent" type="text/html">
        <tr data-bind="click: $root.setLine.bind($data, $index())">
            <td data-bind="click: $root.setCell.bind($data, $element.cellIndex)">
                <span data-bind="text: name"></span>
                <input type="text" data-bind="visible: $root.currentCell() == 0 && $index() == $root.currentLine(),
                                              value: name"/> <!--fixed-->
            </td>
        </tr>
    </script>