gpt4 book ai didi

Javascript findIndex 不是函数

转载 作者:数据小太阳 更新时间:2023-10-29 04:58:58 24 4
gpt4 key购买 nike

我有一个 json 数组:

[    
{"id":19,"name":"Jed", "lastname":"DIAZ", "hobby":"photo", "birthday":"2011/11/22"},
{"id":20,"name":"Judith", "lastname":"HENDERSON", "hobby":"pets", "birthday":"1974/06/12"},
{"id":21,"name":"Nicolai", "lastname":"GRAHAM", "hobby":"reading", "birthday":"2005/01/22"},
{"id":22,"name":"Vasile", "lastname":"BRYANT", "hobby":"singing", "birthday":"1987/03/17"}
]

从 json 数组中删除一个项目的函数

 removeItem: function(removeId){
//paramater validation
return dataLoad.then(function(data){

f = data.findIndex(function(item) { return item.id == removeId; });

if(f < 0)
return false;
data.splice(f,1);

LS.setData(data,"cutomers");

return true;
});
}

代码运行时出现错误:

findIndex is not a function

错误行

 f = data.findIndex(function(item) { return item.id == removeId; });

最佳答案

findIndex 不是 ECMASCRIPT 262Array 的原型(prototype)方法,您可能需要 filterindexOf 结合使用,相反,它的优点是一旦找到条目就停止搜索

var f;
var filteredElements = data.filter(function(item, index) { f = index; return item.id == removeId; });


if (!filteredElements.length) {
return false;
}

data.splice(f, 1);

按照 Nina Scholz 评论中的建议进行编辑:

此解决方案使用 Array.prototype.some相反

var f;
var found = data.some(function(item, index) { f = index; return item.id == removeId; });

if (!found) {
return false;
}

data.splice(f, 1);

发现于 Array.prototype.findIndex MDN

enter image description here

关于Javascript findIndex 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32221747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com