简体   繁体   English

包含数组的JSON对象

[英]JSON Object containing Array

I have JSON,like, 我有JSON之类的

var jsondata = {
  "an_array" : [[2,4],[1,2]]
} 

With JavaScript, I want to use a for loop to go through each element of the array in the array, like, 使用JavaScript,我想使用for循环遍历数组中数组的每个元素,例如,

var grab_array = jsondata.an_array;
for (i = 0; i < grab_array.length; i++) {

 grab_array[i][0]; //doing stuff

}

However, and I know this is probably some serious noob stuff, when I run typeof() on grab_array, it says it is an object and has a length of 0. What should I be doing? 但是,我知道这可能是一些严重的菜鸟问题,当我在grab_array上运行typeof()时,它说这是一个对象,长度为0。我应该怎么做?

Well I can't follow the part with the length being 0 , did you actually run the loop? 好吧,我不能跟随length0那一部分,您实际上运行了循环吗? It should work just fine. 它应该工作正常。

But concerning the typeof operator, that operator (together with instanceof operator) is probably the biggest design flaw of JavaScript. 但是关于typeof运算符,该运算符(与instanceof运算符一起)可能是JavaScript的最大设计缺陷。 It is near of being completely broken . 它快要被完全打破了

Although instanceof still has its limited uses, typeof really has only one practical use case, which not happens to be checking the type of an object. 尽管instanceof仍然有其有限的用途,但typeof实际上仅具有一个实际的用例,而并非恰好在检查对象的类型。

The JavaScript Typetable JavaScript类型表

Value               Class      Type
-------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object (function in Nitro/V8)
new RegExp("meow")  RegExp     object (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object

In the above table Type refers to the value the typeof operator returns. 在上表中,“ 类型”是指typeof运算符返回的值。 As you can see this is anything but consistent. 如您所见,这不是一成不变的。

The Class refers to the value of the internal [[Class]] property of an object. 是指对象内部[[Class]]属性的值。

From the Specification: Class can be one of the following values: "Arguments" , "Array" , "Boolean" , "Date" , "Error" , "Function" , "JSON" , "Math" , "Number" , "Object" , "RegExp" , "String" 根据规范: 可以是以下值之一: "Arguments""Array""Boolean""Date""Error""Function""JSON""Math""Number""Object""RegExp""String"

In order to retrieve the value of Class one can has to make use of the toString method of Object . 为了检索Class的值,必须使用ObjecttoString方法。

Checking the Class of an Object 检查对象的类

function is(type, obj) {
    return Object.prototype.toString.call(obj).slice(8, -1) === type;
}

is('String', 'test'); // true
is('String', new String('test')); // true

In the above code Object.prototype.toString gets called with this being set to the object which its Class value should be retrieved. 在上面的代码Object.prototype.toString被调用与this被设定为它的值应被检索的对象。

Checking whether a variable has been defined 检查是否已定义变量

typeof foo !== 'undefined'

The above will check whether foo was actually declared or not, since just referencing it would result in a ReferenceError . 上面的代码将检查foo是否实际声明,因为仅引用它会导致ReferenceError This is the only thing typeof is actually useful for. 这是typeof实际上唯一有用的东西。

To Sum it up 把它们加起来

Don't use typeof unless you're checking for the existence of a variable. 除非要检查变量是否存在,否则不要使用typeof

Well, as for me, I could easily run this code 好吧,对于我来说,我可以轻松地运行此代码

var jsondata = {
  "an_array" : [[2,4],[1,2]]
}
var grab_array = jsondata.an_array, 
    max = grab_array.length;
for (i = 0; i < max; i++) {

 console.log(grab_array[i][0]); 

}

and the output was pretty expected: 2, 1 (each on new line). 预期的输出是:2、1(每个都在新行上)。 Concerning the second part of the question, you can easily test whether grab_array is an Array or not using following snippet: 关于问题的第二部分,您可以使用以下代码段轻松地测试grab_array是否为数组:

if (grab_array.constructor == Array){
  //do stuff
}

Also in ECMAScript5, you can use has Array.isArray() function, but since you can encounter the case when the destination environment does not support ECMAScript5, you may want to add this universal function for testing if the Object is an Array: 同样在ECMAScript5中,可以使用具有Array.isArray()函数,但是由于遇到目标环境不支持ECMAScript5的情况,因此您可能需要添加此通用函数来测试Object是否为Array:

if (typeof Array.isArray === "undefined") {
 Array.isArray = function (arg) {
  return Object.prototype.toString.call(arg) === "[object Array]";
 };
}

and then simply do: 然后只需执行以下操作:

if (Array.isArray()){
  //do stuff
}

检查类型时,只需使用grab_array.constructor == Array而不是typeof grab_array

I'm not sure what is going on here to be honest. 老实说,我不确定这是怎么回事。 Throwing your code as is through the jQuery JSON parser leads me to a result where an_array.length is 2. typeof still lists it as an object, but it has a length, and your loop should go through it. 通过jQuery JSON解析器按原样抛出代码,将导致我得到一个结果,其中an_array.lengthan_array.length仍将其列为对象,但是它具有长度,循环应该通过它。 More code would probably be helpful. 更多代码可能会有所帮助。

As a debugging tip, trying doing a console.log call in Chrome or Firefox with Firebug of jsondata and see what comes out. 作为调试提示,尝试在Chrome或Firefox中使用jsondata的Firebug进行console.log调用,然后查看结果。 Make sure that the JSON object is coming back correct. 确保JSON对象返回正确。 However, that said, you can also use jQuery utilities to go through each element instead of a for loop. 但是,也就是说,您也可以使用jQuery实用程序遍历每个元素,而不是for循环。 Try using jQuery.each() on it. 尝试在其上使用jQuery.each()

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

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