简体   繁体   中英

Check that a list of variables have each been set

I have an array filled with the names of variables like this:

var myVariables = [variable1,variable2,variable3,variable4];

Is there a simple way besides and each to test if all of these variables have been assigned a value (elsewhere in my code)?

我建议使用Array.some ,通过这种方法,您将不必遍历整个数组:

const hasEmpty = myVariables.some(v => typeof v === 'undefined');

You could use the Array.prototype.some() method :

The some() method tests whether some element in the array passes the test implemented by the provided function.

It could be more efficient than forEach method as it stops iterating (short circuit in a some way) as soon a element matches the condition.

For example to check that all elements are > 0 , use some() with the reverse condition, that is : <=0 .

var isFailed = [0, 1, 2, 3, 4].some(x => x <= 0); 

For example, here, as soon the first iteration, some() exits and return false .

return myVariables.indexOf(undefined) === -1;

If one of your variable is not defined, this will throw a ReferenceError such as mentionned in top comments by Felix Kling. Otherwise if it has the value undefined then you can check if your array contains undefined values.

don't throw Reference Error

If you execute the code below you will get a ReferenceError since variable1 has never been defined.

 const myArray = [variable1] 

But this next code will just create an array with an undefined value in it, since the variable is declared:

let variable1
const myArray = [variable1]

check if undefined is included

With ES 2016 includes() :

const isAllDefined = !myVariables.includes(undefined)
// use this boolean where you need it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM