为什么我的函数中需要此IF语句?

时间:2019-05-22 05:14:12

标签: javascript

所以基本上,我只需要弄清楚为什么我需要在代码中使用if语句...我知道为什么其他代码需要存在,但目前正在学习中。

const todos = [{
    text: 'Order cat food',
    completed: true
}, {
    text: 'Clean kitchen',
    completed: false 
}, { 
    text: 'Buy food',
    completed: true 
}, {
    text: 'Do work',
    completed: false 
}, {
    text: 'exercise',
    completed: true 
}]

const deleteTodo = function (todos, todoText){ 
    const index = todos.findIndex(function (todo){
        return todo.text.toLowerCase() === todoText.toLowerCase()
    })
    if (index > -1) {
        todos.splice(index, 1)
    }
}

deleteTodo(todos, 'Buy food') 
console.log(todos)

3 个答案:

答案 0 :(得分:1)

此行if (index > -1) {正在检查数组中元素的索引。如果该元素存在于数组中,它将返回数字0或大于0。-1表示该元素不存在于数组中。同样,它也在检查数组中是否存在该元素。

因此,如果元素存在于数组中,则将应用splice,它将返回removed项。

答案 1 :(得分:0)

如果该项不在数组中,则Array.findIndex返回-1,执行索引为-1的拼接将导致错误。

答案 2 :(得分:0)

deleteTodo函数将根据提供给它的text从待办事项列表中删除一个项目。如果传递的text不存在,则不应在待办事项的数组上执行splice

请注意,如果文本在其他findIndex中存在,0将返回从length-1-1的数组索引。

例如:-

deleteTodo('eat food');

由于在eat food数组中找不到todos文本,因此上述内容不应更改数组。

考虑一下,如果您要为上述语句执行拼接,则会导致

todos.splice(-1,1)

这将删除todos数组中的最后一项,因为-(减号)表示从数组末尾开始的索引。

相关问题