简体   繁体   English

如何找出一个对象是否是javascript中的数组?

[英]How to find out if an object is an array in javascript?

While going through javascript tutorial on 'W3Schools', I found this bit of code explaining how to to find out if an object is an Array.在浏览关于“W3Schools”的 javascript 教程时,我发现这段代码解释了如何确定对象是否为数组。

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}

I am not understanding how does that particular line executes.我不明白该特定行是如何执行的。

Link to W3School's page in question链接到 W3School 的相关页面

Even if this question has accepted answer about a right way of using Array.isArray()即使这个问题已经接受了关于使用Array.isArray()的正确方法的答案

Question was about executing particular code from W3Schools, so for educational reasons there is what is happening in code example.问题是关于从 W3Schools 执行特定代码,因此出于教育原因,代码示例中发生了什么。

myArray.constructor is reference to object constructor. myArray.constructor是对对象构造函数的引用。 More at Link更多链接

With that in mind, we can proceed to:考虑到这一点,我们可以继续:

myArray.constructor.toString()

Will result into将导致

function Array() { [native code] } function Array() { [本机代码] }

Function indexOf will return position of string sequence in other string sequence.函数indexOf将返回字符串序列在其他字符串序列中的位置。 If string we are looking for is found it will return int position.如果找到我们正在寻找的字符串,它将返回int位置。 If not indexOf will return -1.如果不是indexOf将返回 -1。

Function could be described as If position of "Array" in stringified contructor of object is greater then -1, object is array.函数可以描述为如果对象的字符串化构造函数中“数组”的位置大于-1,则对象是数组。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM