简体   繁体   English

搜索对象数组的JavaScript函数返回undefined而不是object

[英]JavaScript function that searches array of objects returns undefined instead of object

I'm working on a function that searches an array filled with objects (each one has strings, numbers, etc...). 我正在研究一种搜索充满对象的数组的函数(每个数组都有字符串,数字等)。

My function 我的功能

function findPlayer(array, playerToFind){
$.each(array, function(index, el) {
    console.log(el);
    if(el.user_id === playerToFind){
        return el;
    }
}); }

I'm calling it like this (when a button is clicked) I've already checked that $(this).text contains the string value I want. 我这样称呼它(单击按钮时),我已经检查过$(this).text是否包含我想要的字符串值。 That string is somewhere in the arrayWithData and I want the full object. 该字符串在arrayWithData中的某个位置,我需要完整的对象。

var player = findPlayer(arrayWithData,$(this).text());
    console.log(player);

But "undefined" is returned. 但是返回“未定义”。 Why? 为什么? Thanks in advance. 提前致谢。

Because findPlayer is calling .each() and the return statement is in the callback you pass to .each() , you're only returning from the callback, not the original function. 因为findPlayer正在调用.each() ,并且return语句在传递给.each()的回调中,所以您仅从回调中返回,而不是原始函数。

Remember, you're passing the callback to jQuery, and jQuery is invoking it for you on every iteration, which means jQuery internally is receiving the value from your return statement. 记住,您是回调传递给jQuery,而jQuery会在每次迭代时为您调用它,这意味着jQuery在内部从您的return语句接收值。

Since you're abstracting the search operation behind the findPlayer anyway, I'd ditch .each() and just use a regular loop. 由于无论如何您都是在findPlayer后面抽象搜索操作,因此我findPlayer.each()并仅使用了常规循环。

function findPlayer(array, playerToFind){
    for (var i=0; i < array.length; i++)
        if(array[i].user_id === playerToFind)
            return array[i];
}

Will be faster this way too. 这样也会更快。


Note that in ECMAScript 6, you'll be able to use the .find() method. 请注意,在ECMAScript 6中,您将可以使用.find()方法。

function findPlayer(array, playerToFind){
    return array.find(function(el) {
        return el.user_id === playerToFind;
    });
}

Both of these solutions have the advantage of both being native and short circuiting the loop. 这两种解决方案都具有本机和使环路短路的优点。

findPlayer returns undefined because you don't have it returning any value. findPlayer返回undefined,因为您没有返回任何值。

You could modify the function to be closer to this: 可以修改函数以使其更接近于此:

function findPlayer(array, playerToFind) {
  var foundPlayer;

  $.each(array, function(index, el) {
      if (el.user_id === playerToFind) {
        foundPlayer = el;
        return false;
      }
  }); 

  return foundPlayer;
}

Personally I probably wouldn't do this, instead I'd either just simply iterate with a for loop, or use something like lodash/underscore's find method. 就我个人而言,我可能不会这样做,相反,我只是简单地使用for循环进行迭代,或者使用类似lodash / underscore的find方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM