Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple string split is returning object instead array

I'm trying a simple string split in NodeJS, but it is returning an object, not array.

var mytext = "a,b,c,d,e,f,g,h,i,j,k";
var arr = mytext.split(",");
console.log(typeof mytext); <======= output string
console.log(typeof arr);    <======= output object

jsfiddle: http://jsfiddle.net/f4NnQ/

why?

like image 564
user3175226 Avatar asked Apr 01 '14 13:04

user3175226


People also ask

Does string split return an array?

The split() method splits a string into an array of substrings. The split() method returns the new array.

What is the return type of split method of string?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.

Can you use split on an array?

Use the array_split() method, pass in the array you want to split and the number of splits you want to do.

Does split return anything?

The . split() method is a beneficial tool for manipulating strings. It returns a list of strings after the main string is separated by a delimiter. The method returns one or more new strings and the substrings also get returned in the list datatype.


2 Answers

The output of String.prototype.split is an Array and that is an Object.

console.log(typeof []);
// object

You can confirm that the returned object is an array, like this

console.log(Object.prototype.toString.call(arr));
// [object Array]
console.log(arr);
// [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k' ]

Quoting from the MDN Documentation of String.prototype.split,

The split() method splits a String object into an array of strings by separating the string into substrings.

like image 90
thefourtheye Avatar answered Sep 27 '22 20:09

thefourtheye


Arrays are objects in javascript.

If you want to check if its an array -

you can do -

Array.isArray(arr)

like image 42
Mohammad Adil Avatar answered Sep 27 '22 19:09

Mohammad Adil