如何在KnockoutJS中使用indexOf [英] How to use indexOf in KnockoutJS

查看:88
本文介绍了如何在KnockoutJS中使用indexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到的所有在KnockoutJS中使用IndexOf()方法的示例都是基本的字符串类型.我想知道的是如何根据对象变量之一返回作为对象的数组的索引.

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.

推荐答案

observableArray公开了一个名为indexOf的方法,该方法是ko.utils.arrayIndexOf的包装,该方法只是循环遍历数组以查找传递给它的项目

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

如果您只有键之类的东西,那么KO确实有一个名为ko.utils.arrayFirst的实用程序函数,该函数仅循环遍历数组以尝试匹配传递给它的条件.但是,它将返回该项目而不是其索引.获取对象然后在其上调用indexOf效率不高,因为您需要两次遍历数组.

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.

您可以自己编写一个循环来寻找合适的项目,或者基于ko.utils.arrayFirst编写一个通用函数,如下所示:

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

这篇关于如何在KnockoutJS中使用indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆