如果数组索引值等于 x 和 y 值,如何 return 布尔值

How to return a boolean if array index values are equal to a x & y values

有没有办法检查数组 this.state.allBooks 是否在同一索引中同时包含 id:552name:'book2' 以及 return 是真还是假...我想要尽可能避免使用 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

您可以使用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, name:'book1'},{id:999552, name:'xxxbook2'},{id:264, name:'book3'}];
const found2 = data2.find(({ id, name }) => id === 552 && name === 'book2');
console.log(found2);    // undefined
console.log(!!found2);  // false

我想你可以直接使用 JavaScript 的 method some of the array class。如果数组中的任何元素与给定的谓词匹配,有些将 return 为真,因此以下代码应该可以解决问题:

let boolValue = this.state.allBooks.some(bookObject => bookObject.id === 552 && bookObject.name === 'book2');

如果数组中的任何元素通过了给定方法的测试,则使用 javascript 的一些数组方法将 return 一个布尔值。这段代码遍历数组检查是否有任何元素的 ID 为 552 且名称为 'book2'。如果它找到任何元素通过此测试,它将 return true 否则为 false。

// Array this.state.allBooks 
const books = [{id:133, name:'book1'}, {id:552, name:'book2'}, {id:264, 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:'book1'},
  {id:552, name:'book2'},
  {id:264, name:'book3'}
];
state.allBooks.map(e=>{
  if(e.id == '552' && e.name == 'book2'){
    boolValue = true;
  }
});
console.log(boolValue)

这是一个工作示例link