Array方法中的Javascript循环
Javascript loop in Array method
当我在数组中有像这样的对象时
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)
中,我不得不调用另一个函数,我可以存储变量
相关文章:
- Javascript循环不会自我更新
- JavaScript循环无法正确计算/显示结果
- JavaScript循环并等待函数
- Javascript:循环属性内部的条件递增或递减
- Array方法中的Javascript循环
- 用于使用javascript循环选择选项
- 中断javascript循环
- 如何在javascript循环中打印代码
- jQuery.ajax()访问javascript循环中的beforeEnd局部变量
- 在qualtrics上使用javascript:循环块中的问题id
- GoogleMapsV3api只显示Javascript循环中的一些标记
- Javascript循环限制为仅1
- 如何将jQueryeach()转换为常规的javascript循环
- 有没有javascript循环的替代方案
- GraphQL代码中的Javascript循环依赖关系
- Javascript循环文本
- JavaScript循环中的HTML
- ..的Javascript..循环中的对象没有在最后一个属性上运行
- JavaScript循环迭代太多
- Javascript循环计算