如何通过索引选择数组中的值?

时间:2017-06-18 18:03:57

标签: javascript arrays reactjs object

我的待办事项如下:

[{id:1,text:"hello"},{id:2,text:"hey"},{id:3,text:"ho"},{id:4,text:"let's go"}]

我很困惑,我需要这样的代码帮助,这是为了反应中的分页:

selectTodosToDisplay = (todos, { index1: 2, index2:3 }) => {
return [...todos.slice(index1, index2), 
        ...todos.slice(index2) ]
}

所以使用上面的代码我想得到这个

[{id:3,text:"ho"},{id:4,text:"let's go"}]

也许还有其他方法吗?帮助

4 个答案:

答案 0 :(得分:0)

Array#slice返回一个新数组,因此您无需将其扩展为新数组。第二个索引应该是4,因为Array#slice以第一个索引中的项开头,并以第二个索引之前的项结束。我们可以在函数中将第二个索引加1。

const todos = [{id:1,text:"hello"},{id:2,text:"hey"},{id:3,text:"ho"},{id:4,text:"let's go"}];

const selectTodosToDisplay = (todos, { index1, index2 }) => todos.slice(index1, index2 + 1);

const result = selectTodosToDisplay(todos, { index1: 2, index2: 3 });

console.log(result);

答案 1 :(得分:0)

var sample = [{ id: 1, text: "hello" }, { id: 2, text: "hey" }, { id: 3, text: "ho" }, { id: 4, text: "let's go" }];
var selectedID = 1;

function filterByID(item) {

    if (item.id == selectedID) {
        return true;
    }
    return false;
}

var arry = sample.filter(filterByID)

我希望它的工作

答案 2 :(得分:0)

JavaScript spread syntax的完美用例:

const [first, second, ...rest] = [{id:1,text:"hello"},{id:2,text:"hey"},{id:3,text:"ho"},{id:4,text:"let's go"}];

console.log(rest);

答案 3 :(得分:0)

selectTodosToDisplay = (todos, { index1: 2, index2:3 }) => todos.slice(index1, index2 + 1)