I have an array of both objects (JSX elements) and strings, which I want to iterate over and perform logic on the items that are strings, but skip the objects.
const array= ['string', {...}, {...}, 'string', 'string', {...}];
for (let i = 0; i < array.length ; i ) { if( {/* This is an object */} ){continue;}else{
{/* perform logic */}}
Is is possible to continue a loop based on type?
CodePudding user response:
The typeof operator should do what you want. However, if the logic you wish to perform only works on strings then you may want to consider inverting your logic to guard against the potential for your array to contain additional data types in the future.
Something like:
const array= ['string', {...}, {...}, 'string', 'string', {...}];
for (let i = 0; i < array.length ; i ) {
const str = array[i]
if( typeof str === 'string'){
/* perform logic on str */
}
CodePudding user response:
See the typeof operator.
eg.
if (typeof array[i] !== 'string') {
continue;
}