'nodejs [] operator, avoid picking first char of array of strings
I have an array of strings that sometimes is an array that only contains one string. when that is the case array[0] does not return the whole string but returns the first char in the string.
I can get around it with some if checking if length is > 1 but it is awful.
is there a safe [] operator or method that always return the whole string in position 0 of the array instead of the first char in the string?
This is an express input-based array in an html form. I don't really have too much control over how it's generated.
i can't use a foreach as I have other parallel arrays from that form.
Solution 1:[1]
Before operating your var as an array, you should verify that it is an array.
In you case, i guess that when you get only a string the provider of your data return a string type and when there is more than one string it return an array of string.
So you need to verify the type returned by your data provider and then process with the right type.
if ( Array.isArray(yourVar) ) {
console.log('My var is an array');
} else {
console.log('My var is not an array');
}
You can also use typeof to check your var type, for example verify that your var is a string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alaindeseine |
