0

I have an algorithm which binds an object from MVC (C#) to the view. The key and the data can be anything, this is up to the implementer.

The issue that I am having is that I cannot determine if something in the JSON string is an array or a simple string. The following code works recursively. If it is an array, it needs to dig deeper. Otherwise, it will bind the value it found based on the key and value.

function constructView(data)
{
    for(var key in data)
    {
        if (data[key].length > 1)
        {
            var count = 0;

            while (count < data.length)
            {
                constructView(data[count]);
                count++;
            }
        }
        $("#" + key).html(data[key]);
    }
}

This is just a prototype, so at the moment it does not generate components but simply does bindings.

Ok, so, the issue:

When I pass in

{"data":"this is a response","strings":["test1","test2"]}

it returns 18 and 2 for lengths. This is because both are technically arrays with a valid length.

Is there a way to get a item length? Where it considers a lone string as 1 item and the array as its respective item count?

I can verify that the JSON array is passed in properly.

Any help is greatly appreciated!

4

4 回答 4

4
Array.isArray(x)

将检查数组,但如果您需要支持旧版浏览器,则需要一个 polyfill(很容易找到)。

typeof x === "string"

将指示一个字符串

于 2013-05-10T01:07:55.210 回答
1

在现代的 ES5 兼容实现中,有Array.isArray

var a = [];
Array.isArray(a); // true

在较旧的实现中,您需要这种丑陋的解决方法:

function isArray(a) {
    return ({}).toString.call(a) === "[object Array]";
    // or: 
    // return Object.prototype.toString.call(a) === "[object Array]";
}
于 2013-05-10T01:08:08.183 回答
0

查看其他答案,但如果您不想担心 polyfill,您似乎已经在使用 jQuery(继续使用$(...).html(...)),那么为什么不使用jQuery 的$.isArray()函数呢?

于 2013-05-10T01:08:51.307 回答
0

由于您使用的是 JQuery,因此您可以使用:

if ($.type(data[key])==="array")
于 2013-05-10T01:09:39.987 回答