我正在用 array.prototype.some() 练习一些东西
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
基本上我想要做的是只要一个数组包含一个填充的字符串值和一些空字符串值。例如,只要数组中有一个填充的字符串值,我就希望它为真。
const array1 = [ 'g', '']; //returns true
const array2 = [ '', '']; //return true
const array3 = [ '', 'x']; //return true
const array4 = [ 'g', 'x']; //return false
// checks whether an element contains at least one populated string (non blank string)
const even = (element) => element === '';
console.log(array1.some(even)); //Should be True
console.log(array2.some(even)); //Should be False
console.log(array3.some(even)); //Should be True
console.log(array4.some(even)); //Should be True
我知道它是因为元素 === '' 但我不知道该写什么才能使它成为我想要的样子,提前致谢!
答案 0 :(得分:1)
反转测试 - 检查某些元素是否不是空字符串:
const array1 = [ 'g', '']; //returns true
const array2 = [ '', '']; //return true
const array3 = [ '', 'x']; //return true
const array4 = [ 'g', 'x']; //return false
// checks whether an element contains at least one populated string (non blank string)
const even = (element) => element !== '';
console.log(array1.some(even)); //Should be True
console.log(array2.some(even)); //Should be False
console.log(array3.some(even)); //Should be True
console.log(array4.some(even)); //Should be True