How to replace a given index element in knockoutjs

后端 未结 5 612
时光说笑
时光说笑 2020-12-15 04:55

How do you replace a given index in an observableArray with another element.

I have: ViewModel.Elements()[index]

how can i replace it with anot

5条回答
  •  佛祖请我去吃肉
    2020-12-15 05:23

    The question asks how to replace "a given index", rather than a given value. The accepted answer works when there are no repetitions in the observableArray, but in case there are repetitions then it will not always behave as expected. E.g. suppose we have:

    index = 2;
    elements = ko.observableArray([9,8,9]);
    

    and then we use the accepted answer.

    elements.replace(elements()[index], 7);
    

    Then elements will be [7,8,9] (because replace uses indexOf, which finds the lowest index of the given value 9), whereas the question surely expects a solution that would make elements be [9,8,7].

    To truly replace with newElement the item at index in an observableArray elements, you can use the following.

    elements(elements.slice(0, index).concat(newElement, elements.slice(index + 1)));
    

    Something more elegant would be nice. Though IIUC it's a question of readability rather than of performance.

提交回复
热议问题