javascript - 为什么 Array.indexOf() 对一个 redux Action 正确工作,但对另一个 Action 却不行? (相同的 reducer )

标签 javascript arrays reactjs redux indexof

var tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5',
            'tag6', 'tag7', 'tag8', 'tag9', 'tag0'];

var selectedTags = [];

const tagsReducer = (state={}, action) => {
    var tagIndex = '';
    if(action.type==="ADD_TAG") {                     //this if statement works as expected
        tagIndex = tags.indexOf(action.payload);
        selectedTags.push(tags[tagIndex]);
        tags.splice(tagIndex, 1);
        return {tags, selectedTags};    
    }
    if(action.type==="REMOVE_TAG"){                          //this doesn't
        tagIndex = selectedTags.indexOf(action.payload);
        console.log(selectedTags);                            //prints the expected array
        console.log(action.payload);                          //prints the expected string
        console.log(tagIndex);                                //prints -1 (doesn't find the string)
        console.log(typeof(selectedTags));                    //prints object
        console.log(typeof(action.payload));                  // prints string
        tags.push(selectedTags[tagIndex]); 
        selectedTags.splice(tagIndex, 1);

        return {tags, selectedTags};
    }
    return {tags, selectedTags}
}

字符串对数组项之一进行数学运算,但 indexOf() 函数仍返回 -1。这很令人困惑,因为第一个 Action 工作正常,但第二个 Action 却没有。有什么建议么?

最佳答案

string mathes one of the array items, but the indexOf() function still returns -1

当您调用 indexOf 时,它匹配数组项之一,因为如果匹配,indexOf 会找到它。 indexOf isn't broken .

所以剩下两种普遍的可能性:

  1. 数组中的字符串看起来应该匹配,但与 payload 中的字符串略有不同。可能不明显的不同方式:

    • 其中一个(array中的那个或者payload中的那个)可以在开头或者结尾有一个空格等。
    • 其中一个可能在大小写上略有不同。
    • 它们的字符可能略有不同,很容易混淆,例如 çç
    • 数组中的条目可能有一个逗号,例如 "thisTag,thatTag" 如果您不匹配 "thatTag",当然不会去看看,虽然它看起来像 "thatTag" 在数组中。
    • 其中一个可能是 String 对象,而另一个是字符串基元; String 对象和字符串原语不是=== 彼此,indexOf 使用=== 测试.
  2. 当您调用 indexOf 时,该字符串不在 selectedTags 数组中,即使它在控制台中看起来是这样。那是因为 this feature of consoles .

为了解决这个问题,在 indexOf 行设置一个断点,当它被击中时,查看 payload 中的字符串和 selectedTags< 中的字符串(如果有——如果没有,那就是控制台的问题)。您会发现一些差异。

关于javascript - 为什么 Array.indexOf() 对一个 redux Action 正确工作,但对另一个 Action 却不行? (相同的 reducer ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114349/

相关文章:

javascript - 从成员方法中访问 javascript 对象引用

javascript - "Notification URL"的替代方案来处理 Node 中长时间运行的 API 进程

javascript - 删除某些元素后如何重新索引对象?

mysql - 如何在laravel中将数组保存到mysql数据库

C++ 数组中最大的数字。正面及负面

javascript - 等待带有 React Hooks 的 Redux Action

javascript - 确保 jQuery 仅在所有 PHP 完全执行后才执行

c# - 如果值匹配,则从另一个字符串数组获取字符串

javascript - 在 ReactJS 中使用表单的最佳实践是什么?

reactjs - Spring API 请求给出 "Content type ' application/octet-stream' not supported"错误,但是使用 Postman 时请求成功