我正在尝试查看我的数据中的值是否与值数组匹配以返回 true 或 false。
这是我到目前为止想出的...
acceptedGrades = ['A1','A2','A3','B1','B2','B3','C1','C2','C3'];
this.state.isValidGrade = _.every(acceptedGrades, d => item.grade === value);
例如如果 item.grade 返回 A1 grade: 'A1'
返回 true,如果 item.grade 返回值不在 acceptedGrades 中则返回 false。
我使用相同的语句通过 hasOwnProperty 搜索属性,这很好,只需要查找属性的值。
可以使用 lodash 库。
最佳答案
有几种方法可以解决这个问题。我认为您正在寻找 find
、filter
、includes
或 findIndex
。 every
不适合这里,因为它正在评估整个数组以确保所有值都满足您的条件。如果我理解正确的话,我认为您只是在尝试将成绩与数组中的项目相匹配。
const acceptedGrades = ['A1','A2','A3','B1','B2','B3','C1','C2','C3'];
// Get first match:
console.log(acceptedGrades.find( g => g === 'B2')); // returns 'B2'
// Get All Matches:
console.log(acceptedGrades.filter( g => g === 'B2')); // returns ['B2']
// Get Index of first match:
console.log(acceptedGrades.findIndex( g => g === 'B2' )); // returns 4
// See if array 'includes' the value
console.log(acceptedGrades.includes('B2')); // returns true
关于javascript - 修正了一些语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281324/