Javascript findIndex 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32221747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript findIndex is not a function
提问by Gigi
I have a json array:
我有一个 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"}
]
function to remove a item from json array
从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;
});
}
When the code is running there is an error:
代码运行时出现错误:
findIndex is not a function
findIndex 不是函数
error line
错误行
f = data.findIndex(function(item) { return item.id == removeId; });
回答by axelduch
findIndex
is not a prototype method of Array
in ECMASCRIPT 262, you might need filter
combined with indexOf
, instead, it has the advantage of stopping searching as soon as entry is found
findIndex
不是的原型方法Array
中的EcmaScript 262,你可能需要filter
联合indexOf
,相反,它具有停止尽快搜索的优势,找到条目
var f;
var filteredElements = data.filter(function(item, index) { f = index; return item.id == removeId; });
if (!filteredElements.length) {
return false;
}
data.splice(f, 1);
EDIT as suggested in comments by Nina Scholz:
按照Nina Scholz评论中的建议进行编辑:
This solution is using Array.prototype.some
instead
该解决方案是使用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);
Found at Array.prototype.findIndex MDN
回答by Oskar Eriksson
I think you'll find your answer in your own headline; you're probably looking for indexOf, instead of findIndex. findIndex is a part of ECMAScript2015 and isn't very widely supported yet.
我想你会在自己的标题中找到答案;您可能正在寻找 indexOf,而不是 findIndex。findIndex 是 ECMAScript2015 的一部分,尚未得到广泛支持。
According to MDN, findIndex is only supported in Firefox 25+ and Safari 7.1+, so if you're testing in any other browser you'd get the error you're having.
根据MDN, findIndex 仅在 Firefox 25+ 和 Safari 7.1+ 中受支持,因此如果您在任何其他浏览器中进行测试,您会遇到您遇到的错误。
There is a suggested polyfill att the MDN page that you can use if you want to use findIndex today.
如果您今天想使用 findIndex,则可以在 MDN 页面上使用建议的 polyfill。