在数组中查找字符串

发布于 2024-12-11 21:39:24 字数 319 浏览 0 评论 0原文

如何查找/匹配数组中的字符串?

如何在此范围内进行搜索?
在此处输入图像描述

例如,如果 likes[3].id 是“99999”,这就是我想要搜索的内容对于...我怎么能这样做?

我尝试过这个:

var likes = response.data
jQuery.inArray(99999, likes)

但没有任何运气......

提前谢谢你。

How do I find/match a string in an array?

How can I search within this?

enter image description here

If for example the likes[3].id was "99999" and that was what I wanted to search for... How could I do this??

I tried this:

var likes = response.data
jQuery.inArray(99999, likes)

But without any luck...

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

留一抹残留的笑 2024-12-18 21:39:24

inArray 只会搜索数组中的顶级对象,因为您需要查找对象上的属性值,您需要执行类似的操作(未测试) -

var found = false;
var indexFoundAt = -1;
jQuery.each(likes,function(index, value) {
   if (value.id == "99999") {
     found = true;
     indexFoundAt = index;
     return false;  
  }
})

inArray will only search the top level objects in your array, as you need to find the value of a property on an object you'd need to do something like (not tested) -

var found = false;
var indexFoundAt = -1;
jQuery.each(likes,function(index, value) {
   if (value.id == "99999") {
     found = true;
     indexFoundAt = index;
     return false;  
  }
})
久随 2024-12-18 21:39:24

如果我理解正确的话,您需要在每个对象的 id 属性内的对象数组中找到一个字符串。

所以我建议

function findId(id_needed)
{
  var found = 0;
  var arrayResult = []
  var likes = [] //your array of objects ofcaurse should be filled some how

  for(var i = 0;i<likes.length;i++)
  {
    if(likes[i].id==id_needed)
    {
      arrayResult[arrayResult.length]=likes[i];
      found +=1;
    }
  }
  return {Found : ((found>0)?(true):(false )),Result : arrayResult}
}

这个函数将返回一个具有 2 个属性的对象

  1. Found - [true/false]
  2. 结果 - 具有所需 id 的对象数组

If I understood you right, you need to find a string in an array of objects within the id property of each object.

So here's what I suggest

function findId(id_needed)
{
  var found = 0;
  var arrayResult = []
  var likes = [] //your array of objects ofcaurse should be filled some how

  for(var i = 0;i<likes.length;i++)
  {
    if(likes[i].id==id_needed)
    {
      arrayResult[arrayResult.length]=likes[i];
      found +=1;
    }
  }
  return {Found : ((found>0)?(true):(false )),Result : arrayResult}
}

this function will return an object with 2 properties

  1. Found - [true/false]
  2. Result - array of objects with needed ids
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文