Javascript findIndex不是一个函数 [英] Javascript findIndex is not a function

查看:773
本文介绍了Javascript findIndex不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json数组:

  [
{id:19,name: Jed,姓氏:DIAZ,爱好:照片,生日:2011/11/22},
{id:20,name:Judith ,姓:HENDERSON,爱好:宠物,生日:1974/06/12},
{id:21,name:Nicolai,姓氏:GRAHAM,业余爱好:阅读,生日:2005/01/22},
{id:22,name:Vasile,lastname :BRYANT,业余爱好:唱歌,生日:1987/03/17}
]

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

  removeItem:function(removeId){
//参数验证
返回dataLoad.then(函数(数据){

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

如果(f <0)
返回false;
data.splice(f,1);

LS.setData(数据,cutomers );

返回true;
});
}

当代码运行时出现错误:


findIndex不是函数


错误行

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


解决方案

findIndex 不是


I have a json array:

[    
  {"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

 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

error line

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

解决方案

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

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:

This solution is using Array.prototype.some instead

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

这篇关于Javascript findIndex不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆