最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

getting object instead of array in javascript - Stack Overflow

programmeradmin2浏览0评论

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"]

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"]
Share Improve this question asked Dec 3, 2015 at 16:40 iromirom 3,60617 gold badges59 silver badges92 bronze badges 7
  • 5 Arrays are objects in JS, and typeof returns "object" when testing an array. As you can see, you have an array. – Teemu Commented Dec 3, 2015 at 16:42
  • 2 And use Array.isArray(con) to test for an array. Arrays are objects in JS. – AtheistP3ace Commented Dec 3, 2015 at 16:45
  • 1 Also typeof is... special. – Felix Kling Commented Dec 3, 2015 at 16:46
  • @FelixKling, it seems you've misspelled "useless"...FTFY. – zzzzBov Commented Dec 3, 2015 at 16:47
  • 1 @zzzzBov: It's still good for testing for functions ;) – Felix Kling Commented Dec 3, 2015 at 16:47
 |  Show 2 more ments

2 Answers 2

Reset to default 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 patibility:

function isArray(arr) {
  return Object.prototype.toString.call(arr) === '[object Array]';
}

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+/); 
发布评论

评论列表(0)

  1. 暂无评论