How to use indexOf in KnockoutJS

江枫思渺然 提交于 2019-12-20 10:18:20

问题


All the examples I see of using the IndexOf() method in KnockoutJS are of basic string types. What I want to know is how to return the index of a array that is an object, based on one of the object variables.


回答1:


An observableArray exposes a method called indexOf, which is a wrapper to ko.utils.arrayIndexOf that simply loops through the array looking for the item that you pass to it.

So, if you have the item you can do:

var viewModel = {
   items: ko.observableArray([{id: 1, name: "one"}, {id:2, name: "two"}])
};

var item = viewModel.items()[1];

console.log(viewModel.items.indexOf(item)); //equals 1

If you just have something like a key, then KO does have a utility function called ko.utils.arrayFirst that just loops through the array trying to match the condition that you pass to it. However, it returns the item and not the index of it. It would be slightly inefficient to get the object and then call indexOf on it, as you would make two passes through the array.

You could just write a loop yourself looking for the right item or write a generic function based on ko.utils.arrayFirst that would look like:

function arrayFirstIndexOf(array, predicate, predicateOwner) {
    for (var i = 0, j = array.length; i < j; i++) {
        if (predicate.call(predicateOwner, array[i])) {
            return i;
        }
    }
    return -1;
}

Now, you can pass an array, a condition, and you will be returned the index of the first item that matches.

var viewModel = {
    items: ko.observableArray([{
        id: 1,
        name: "one"},
    {
        id: 2,
        name: "two"}])
};

var id = 2;

console.log(arrayFirstIndexOf(viewModel.items(), function(item) {
   return item.id === id;    
})); //returns 1


来源:https://stackoverflow.com/questions/6926155/how-to-use-indexof-in-knockoutjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!