简体   繁体   English

如何从javascript对象中找到属性类型?

[英]How to find a property type from javascript object?

How can I find out which property of an object is an Array type? 我如何找出对象的哪个属性是数组类型? Given the sample code below, I would expect to get the value OrderItemList . 给定下面的示例代码,我希望获得值OrderItemList

function Order() {
    this.Id = 0;
    this.LocationID = 0;
    this.OrderItemList = new Array();      
}

var orderObject = new Order();

From what I understand, you have an Object in javascript and you want to know if it contains an Array or not. 据我了解,您在javascript中有一个Object,并且想知道它是否包含Array。 If that's what you want to achieve you can simply traverse through all the keys for that object and check if the value is an instanceOf array. 如果这是您想要实现的目标,则可以简单地遍历该对象的所有keys ,然后检查该值是否为instanceOf数组。

In Jquery, you could do something like this ( updated Demo ): 在Jquery中,您可以执行以下操作( 更新了Demo ):

$.each( orderObject, function( key, value ) {
if(value instanceof Array){
   console.log(key);
  }
});

Javascript equivalent: 等效的Javascript:

for (var key in orderObject) {
 var val = orderObject[key];
  if (val instanceof Array){
   console.log(key);    
  }
}

I hope it gets you started in the right direction. 我希望它可以帮助您朝正确的方向开始。

Edit - Like many have already pointed length attribute can not be used to uniquely distinguish an array from a string although you could do a typeof check to see if the value is a string. 编辑 -像许多已经指出length属性不能被用来从一个字符串唯一区别数组虽然你可以做typeof检查,看看是否值是一个字符串。

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

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