4

I have string data[2] which in test is "6766 44 9 19904 7772 13323 245 14 221" and trying to convert it to array using code below

console.log(typeof(data[2]),data[2].length,data[2]);
con = data[2].trim().split("\\s+"); // i.e. 66 44 9 19904 7772 13323 245 14 221
console.log(typeof(con),con.length,con);

But getting below object instead, please advice

string 38  6766 44 9 19904 7772 13323 245 14 221
object 1 ["6766 44 9 19904 7772 13323 245 14 221"]
7
  • 5
    Arrays are objects in JS, and typeof returns "object" when testing an array. As you can see, you have an array. Commented Dec 3, 2015 at 16:42
  • 2
    And use Array.isArray(con) to test for an array. Arrays are objects in JS. Commented Dec 3, 2015 at 16:45
  • 1
    Also typeof is... special. Commented Dec 3, 2015 at 16:46
  • @FelixKling, it seems you've misspelled "useless"...FTFY. Commented Dec 3, 2015 at 16:47
  • 1
    @zzzzBov: It's still good for testing for functions ;) Commented Dec 3, 2015 at 16:47

2 Answers 2

9

You're trying to use a string to split instead of a regex:

change .split("\\s+") to .split(/\s+/g).

The typeof operation will return "object" for arrays, so you're actually seeing an array with a single item, which is why your count is wrong.

If you want to check if an object is an array, use Array.isArray, or for compatibility:

function isArray(arr) {
  return Object.prototype.toString.call(arr) === '[object Array]';
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is the g flag necessary here?
@axelduch, probably not, but I recall some methods only match the first instance, and this appears to be a case where splitting should happen on all spaces, so the g flag makes sense to me. I honestly hadn't tested it.
Split is implicitly global already, but it is true for methods like String.prototype.replace
5

This is incorrect because you split by a string but could be a regexp:

con = data[2].trim().split("\\s+"); 

Could be

con = data[2].trim().split(/\s+/); 

1 Comment

"could be" no "should be"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.