Array方法中的Javascript循环

Javascript loop in Array method

本文关键字:Javascript 循环 方法 Array      更新时间:2023-09-26

当我在数组中有像这样的对象时

    var bookIndex =  [{
      id: '1',
      title: 'First title',
      description: 'This is my first title'
    }, {
      id: '2',
      title: 'Second title',
      description: 'This is my second title'
    }];

然后使用for()循环遍历数组

    function getBook(bookId){
      for (var i = 0; i < bookIndex.length; i++) {
        if (bookIndex[i].id === bookId) {
          return bookIndex[i];
        }
       }
       return undefined;
     };

我想知道如何使用其他循环方法,以获得相同的结果。Ex.for Each。我尝试使用类似的东西,但它无法获得我想要的返回对象。

    function getBook(bookId) {
      bookIndex.forEach(function () {
        if (bookId === bookIndex.id) {
          return bookId;
        }
        return undefined;
      });
    };

您可以使用.find():

function getBook(bookId) {
  return bookIndex.find(function(book) { return book.id === bookId; });
}

当满足条件时,对.find()的回调应该返回true。当这种情况发生时,.find()返回数组的那个元素。如果没有元素匹配,则返回undefined

.forEach()函数很有用,但它确实适用于实际想要对数组的每个元素执行某些操作的情况。

您可以使用filter并返回具有该id的对象。

var bookIndex = [{
   id: '1',
   title: 'First title',
   description: 'This is my first title'
 }, {
   id: '2',
   title: 'Second title',
   description: 'This is my second title'
 }];
 function getBook(bookId) {
    return bookIndex.filter((e) => { return parseInt(e.id) == parseInt(bookId)})[0];
 };
 
 console.log(getBook(2))

您可以使用Array#some()

some()方法测试数组中的某个元素是否通过了所提供函数实现的测试。

function getBook(bookId) {  // returns true or false if the book exists
    return bookIndex.some(function (book) {
        return bookId === book.id;
    });
};

对于返回图书对象,则可以使用

function getBook(bookId) {  // returns the book with the index
    var book;
    bookIndex.some(function (b) {
        if (bookId === b.id) {
           book = b;
           return true;
        }
    });
    return book;
};

我让你想知道你怎么能循环然后返回,由于每个女巫都回答了你没有使用每个女巫,我想向你展示一个foreach解决方案,希望这是你所期望的

var bookIndex = [
    {
        id: '1',
        title: 'First title',
        description: 'This is my first title'
    }, {
        id: '2',
        title: 'Second title',
        description: 'This is my second title'
    }];
function getBook(bookId) {
    bookIndex.forEach( function (el) {
        if (el.id === bookId) {
          getBook1(el);
        }
    });
}
getBook('2');
function getBook1(el) {
 var element = el;
    console.log(element);
}

bookIndex.forEach( function (el)中,您需要向用于forEach方法的函数(回调)传递一个参数。这是你的主要错误。我传递的这个名为el的elment基本上是数组中的每个元素witch都不是未定义或null。由于你不能只从foreach返回一些东西,因为它返回到回调,而不是parrent函数,在你的例子function getBook(index)中,我不得不调用另一个函数,我可以存储变量