admin管理员组

文章数量:1415145

My iteration has been working fine and dandy until know. I've encountered myself with an empty array and the .every() method doesn't work with that kind of values.

Here's the validation:

if(oJSonElementByIndex[sColumnName].every(x => typeof x == 'number'))

¿Any other options? Thanks in advance.

My iteration has been working fine and dandy until know. I've encountered myself with an empty array and the .every() method doesn't work with that kind of values.

Here's the validation:

if(oJSonElementByIndex[sColumnName].every(x => typeof x == 'number'))

¿Any other options? Thanks in advance.

Share Improve this question asked Jun 14, 2018 at 14:00 Jose PeresJose Peres 3171 gold badge2 silver badges19 bronze badges 6
  • 3 What do you mean it doesn't work? What exactly do you want to achieve? – bugs Commented Jun 14, 2018 at 14:01
  • I think the one line of code is quite self-explaining in terms of what he wants to achieve... – Rob Commented Jun 14, 2018 at 14:02
  • @Robert not really... the question as a whole requires clarification – bugs Commented Jun 14, 2018 at 14:03
  • 3 Every value of an empty array verifies any predicate you want. If that's not to your taste, you might want to test whether the array is empty beforehand, i.e. if(array.length > 0 && array.every(predicate)) – Aaron Commented Jun 14, 2018 at 14:03
  • "I've encountered myself with an empty array and the .every() method doesn't work with that kind of values". If you have an object like this one: "key": [], the every() method won't suffice. – Jose Peres Commented Jun 14, 2018 at 14:04
 |  Show 1 more ment

2 Answers 2

Reset to default 7

If there is no element in the array, every element in the array fullfills the condition. Therefore it returns true. To achieve the opposite:

arr.length && arr.every(/*...*/)

So the ment about "every" predicate being fulfilled on an empty array, and the ment about using array.length and not just the array led me to putting together this snippet to illustrate.

The things to note here are the truthiness of an empty array, the falsiness of an empty array's length--zero, and the somewhat unintuitive logic idea that if you have no predicates then all none of them passed the condition:

const empty = []
const typeofNumber = (x) => ( typeof x === 'number' )

console.log(`an empty array will return ${empty.every(typeofNumber)} on an every, since "every" predicate fulfilled the condition`)

if(empty.length && empty.every(typeofNumber)) {
  console.log('empty array length and every are truthy')
} else {
  console.log('empty array length and every are falsey')
}

if(empty && empty.every(typeofNumber)) {
  console.log('empty array and every are truthy')
} else {
  console.log('empty array and every are falsey')
}

本文标签: javascriptIs there a method like every() for arrays with empty valuesStack Overflow