如何解决如果数组索引值等于x和y值,如何返回布尔值
有没有一种方法可以检查数组this.state.allBooks
是否在同一索引中同时包含id:552
和name:'book2'
并返回true或false ...我想避免使用for循环如果可能的话。
// Array this.state.allBooks
O:{id:133,name:'book1'}
1:{id:552,name:'book2'}
2:{id:264,name:'book3'}
以前,我已经完成了类似于以下代码的操作,但是由于数组this.state.allBooks
具有ID和名称,因此我不确定采用哪种方法。
let boolValue = this.state.allBooks.includes(/* check if it includes a single value*/)
//Desired output
// 1.0) Does this.state.allBooks include both id:552 and name:'book2' in the same index ?
// a) if yes return true ... should be yes since both id:552 and name:'book2' are part of the same index '1'
// b) if no return false
解决方法
我认为您可以只使用JavaScript的method some
of the array class。如果数组中的任何元素与给定谓词匹配,则某些函数将返回true,因此以下代码应能解决问题:
let boolValue = this.state.allBooks.some(bookObject => bookObject.id === 552 && bookObject.name === 'book2');
,
您可以使用Array.prototype.find
搜索条目。但是,请注意,在内部,涉及搜索和过滤的Array方法的实现总会涉及某种for
循环。
const data1 = [{id:133,name:'book1'},{id:552,name:'book2'},{id:264,name:'book3'}];
const found1 = data1.find(({ id,name }) => id === 552 && name === 'book2');
console.log(found1); // { id: 552,name: 'book2' }
console.log(!!found1); // true
// Let's mutate the entry so it will not be found,for testing
const data2 = [{id:133,{id:999552,name:'xxxbook2'},name:'book3'}];
const found2 = data2.find(({ id,name }) => id === 552 && name === 'book2');
console.log(found2); // undefined
console.log(!!found2); // false
,
如果数组中的任何元素通过了对该方法的测试,则使用javascript的array方法将返回一个布尔值。在这里,此代码遍历数组,检查是否有任何元素的id为552,名称为'book2'。如果它找到任何要通过此测试的元素,它将返回true,否则返回false。
// Array this.state.allBooks
const books = [{id:133,name:'book3'},]
let isObjIn = books.some(book => book.id === 552 && book.name === 'book2');
console.log(isObjIn); // logs true
,
您好,您可以使用地图功能
let state:any = {};
let boolValue:boolean = false;
state.allBooks = [
{id:133,name:'book3'}
];
state.allBooks.map(e=>{
if(e.id == '552' && e.name == 'book2'){
boolValue = true;
}
});
console.log(boolValue)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。