Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - 如何检查对象是否为数组?(How to check if an object is an array?)

I'm trying to write a function that either accepts a list of strings, or a single string.(我正在尝试编写一个接受字符串列表或单个字符串的函数。)

If it's a string, then I want to convert it to an array with just the one item.(如果是字符串,那么我想将其转换为仅包含一项的数组。) Then I can loop over it without fear of an error.(然后,我可以循环浏览它而不必担心错误。) So how do I check if the variable is an array?(那么,如何检查变量是否为数组?) I've rounded up the various solutions below and created a jsperf test .(我整理了以下各种解决方案,并创建了jsperf测试 。) They're all fast, so just use Array.isArray -- it's well-supported now and works across frames .(它们都非常快,因此只需使用Array.isArray -现在得到很好的支持,并且可以跨框架使用 。)   ask by mpen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype .(ECMAScript标准中提供的用于找到Object类的方法是使用Object.prototypetoString方法。)

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) { alert( 'Array!' ); } Or you could use typeof to test if it is a String:(或者,您可以使用typeof来测试它是否为字符串:) if( typeof someVar === 'string' ) { someVar = [ someVar ]; } Or if you're not concerned about performance, you could just do a concat to a new empty Array.(或者,如果你不关心性能,你可以只是做一个concat到一个新的空数组。) someVar = [].concat( someVar ); There's also the constructor which you can query directly:(还有一个可以直接查询的构造函数:) if (somevar.constructor.name == "Array") { // do something } Check out a thorough treatment from @TJ Crowder's blog, as posted in his comment below.(请查看@TJ Crowder博客的详细处理方法 ,如下面他的评论中所述。) Check out this benchmark to get an idea which method performs better: http://jsben.ch/#/QgYAV(查看此基准测试 ,以了解哪种方法效果更好: http : //jsben.ch/#/QgYAV) From @Bharath convert string to array using Es6 for the question asked:(从@Bharath使用Es6将字符串转换为数组以解决以下问题:) const convertStringToArray = (object) => { return (typeof object === 'string') ? Array(object) : object } suppose:(假设:) let m = 'bla' let n = ['bla','Meow'] let y = convertStringToArray(m) let z = convertStringToArray(n) console.log('check y: '+JSON.stringify(y)) . // check y: ['bla'] console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...