Javascript array.indexof在字符串中找不到项目

问题描述 投票:0回答:3
array = on,8816.32,9032.32,8990.167,9038.167,8819.389,9035.389,9059.525,8813.568,9056.726

上面是一个字符串。下面是将值传递给函数trimList的onclick。

 <input type="checkbox" value="9032.32" id="sendpids" onclick="trimList(9032.32)">

使用此处显示的功能https://stackoverflow.com/a/4272526/1794918。我做到了。

    function trimList(cutThis) {

        function remove(array,to_remove)
        {
            const elements = array.split(",");
            const remove_index = elements.indexOf(to_remove);
            console.log(remove_index);
            elements.slice(1, remove_index);
            const result = elements.join(",");
            return result;
        }
        let array = checkedList.ids;
        let newList = remove(array, cutThis);
        checkedList.ids = newList;
        console.log(checkedList.ids);
    }

在控制台日志中,remove_index始终为-1,这意味着它未在数组中找到变量cutThis。当它重新加入列表时。它从列表中删除最后一个项目,而不是提交的项目。

如果我删除元素= array.split(“,”);并只保留elements = array;我可以在控制台日志中看到数字3。

似乎无法将正确的组合组合在一起以实现所需的结果。

在页面上,有一个复选框列表。我具有从这些复选框创建值列表的系统。那就是上面的数组。现在,我试图在未选中此框的情况下从列表中删除该项目。在这种情况下,未选中9032.32

,需要搜索该字符串并将其从列表中删除,然后创建一个新字符串并将其设置为checkedList.ids的全局值。

array = on,8816.32,9032.32,8990.167,9038.167,8819.389,9035.389,9059.525,8813.568,9056.726以上是一个字符串。下面是将值传递给函数trimList的onclick。

javascript arrays
3个回答
0
投票

假设checkedList.ids是您指定的格式的字符串,则有两个问题


0
投票

您正在将要删除的元素作为数字传递。但是您的数组是一个字符串数组。将您的代码更改为这样。


0
投票

分割给出一个字符串数组。您需要将数字转换为字符串才能找到索引。

© www.soinside.com 2019 - 2024. All rights reserved.