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

查看:28
本文介绍了如何在 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天全站免登陆