带有嵌套循环的 JavaScript 嵌套数组

发布于 2024-12-08 14:06:24 字数 1148 浏览 0 评论 0 原文

到目前为止,我尽我所能创建了一个嵌套数组,但我觉得我做错了或者有些事情没有意义。谁能看一下并告诉我我的数组是否是构建嵌套数组的方法。我想要的只是在特定标题下创建行,因此我嵌套数据并使用嵌套循环调用它。也许有一种更简单的方法来实现它。这是代码:

var data = [

    {title:'Row Title 1'},

    [{leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'}],

    {title:'Row Title 2'},

    [{leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'}]

    ];

    for (var i=0, j=data.length; i < j; i++) {

        if(data[i].title != null){
            document.write('<b>'+data[i].title+'</b><br />');
        }

        for(p=0,plen=data[i].length; p<plen;p++){
            document.write('<p style="background:#eee;">'+data[i][p].leftCol+'</p>');
            document.write('<p>'+data[i][p].rightCol+'</p>');       
        }
    }

I created a nested array as I could so far but I feel like i did it wrong or something does not make sense. Could anyone please have a look and tell me if my array is the way to build nested array. All I want is to create rows under specific title, so I nested data and calling it with nested loops. Maybe theres is a simpler way of achiving it. Here is the code:

var data = [

    {title:'Row Title 1'},

    [{leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'}],

    {title:'Row Title 2'},

    [{leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'},
    {leftCol:'Some text for left column',rightCol:'Some text for right column'}]

    ];

    for (var i=0, j=data.length; i < j; i++) {

        if(data[i].title != null){
            document.write('<b>'+data[i].title+'</b><br />');
        }

        for(p=0,plen=data[i].length; p<plen;p++){
            document.write('<p style="background:#eee;">'+data[i][p].leftCol+'</p>');
            document.write('<p>'+data[i][p].rightCol+'</p>');       
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兔小萌 2024-12-15 14:06:24

您使用的结构应该更像这样:

var data = [

    {title:'Row Title 1', contents: [

      {leftCol:'Some text for left column',rightCol:'Some text for right column'},
      {leftCol:'Some text for left column',rightCol:'Some text for right column'},
      {leftCol:'Some text for left column',rightCol:'Some text for right column'}

    ],

    // ...
];

这样,每一行都是一个具有“标题”属性和“内容”属性的对象。你的循环将如下所示:

for (var i=0, j=data.length; i < j; i++) {

    if(data[i].title != null){
        document.write('<b>'+data[i].title+'</b><br />');
    }

    for(var p=0, plen=data[i].contents.length; p < plen; p++){
        document.write('<p style="background:#eee;">'+data[i].contents[p].leftCol+'</p>');
        document.write('<p>'+data[i].contents[p].rightCol+'</p>');       
    }
}

The structure you're using should be more like this:

var data = [

    {title:'Row Title 1', contents: [

      {leftCol:'Some text for left column',rightCol:'Some text for right column'},
      {leftCol:'Some text for left column',rightCol:'Some text for right column'},
      {leftCol:'Some text for left column',rightCol:'Some text for right column'}

    ],

    // ...
];

That way, each row is an object with a "title" attribute and a "contents" attribute. Your loop would then look like this:

for (var i=0, j=data.length; i < j; i++) {

    if(data[i].title != null){
        document.write('<b>'+data[i].title+'</b><br />');
    }

    for(var p=0, plen=data[i].contents.length; p < plen; p++){
        document.write('<p style="background:#eee;">'+data[i].contents[p].leftCol+'</p>');
        document.write('<p>'+data[i].contents[p].rightCol+'</p>');       
    }
}
早乙女 2024-12-15 14:06:24

如果您想让代码更加健壮,请遵循以下准则:

  1. 如果您有长度,最好像这样初始化 for 循环:for (var i = 0, l = length; l--; i++). Nicholas C. Zakas 更详细地解释了这种语法的原因
  2. 始终将多次访问的变量存储在局部变量中。它可以加快执行速度(例如idata = data[i];)。
  3. 尽可能避免鸭子类型(例如data[i].title != null)。首先检查变量的类型。它速度较慢,但​​代码更易于理解和维护。尝试帖子底部的 typeOf 函数(例如 typeOf(idata) === "Object")。
  4. 通常,使用 === 而不是 ==!== 而不是 != 总是更好,因为它们不执行可能导致意外结果的类型强制。
  5. 不要创建多个内联样式,而是创建一个类 .greyBackground { background-color: #EEEEEE; } 并将每个 leftCol 段落的 className 设置为 greyBackground
  6. 避免使用document.write。它很慢,会导致文档回流,并在页面下载时停止加载资源。使用 JavaScript 创建动态内容的最佳方法是使用 document.createDocumentFragment 方法,我将在下面解释。
  7. 自己在 JavaScript 中创建节点总是更好。如果您在 document.writeelement.innerHTML 中使用字符串,则浏览器会解析该字符串并将其转换为节点。因此使用该方法速度较慢。

这就是我编写 JavaScript 的方式:

var data = [
    "Row Title 1",
    {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    },
    "Row Title 2",
    {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }
];

function typeOf(value) {
    if (value === null) {
        return "null";
    } else if (typeof value === "undefined") {
        return "undefined";
    } else {
        return Object.prototype.toString.call(value).slice(8, -1);
    }
}

var element;
var fragment = document.createDocumentFragment();
var idata;

for (var i = 0, l = data.length; l--; i++) {
    idata = data[i];
    if (typeOf(idata) === "Object") {
        element = document.createElement("p");
        element.className = "greyBackground";
        element.appendChild(document.createTextNode(idata.leftCol));
        fragment.appendChild(element);

        element = document.createElement("p");
        element.appendChild(document.createTextNode(idata.rightCol));
        fragment.appendChild(element);
    } else {
        element = document.createElement("b");
        element.appendChild(document.createTextNode(idata));
        fragment.appendChild(element);

        element = document.createElement("br");
        fragment.appendChild(element);
    }
}

document.body.appendChild(fragment);

测试我的页面和你的页面。很可能我的执行速度会更快。如果您有任何疑问,请随时问我。干杯! =)

If you want to make your code more robust follow these guidelines:

  1. It's always better to initialize for loops like so if you have a length: for (var i = 0, l = length; l--; i++). The reason for this syntax is explained in fuller detail by Nicholas C. Zakas.
  2. Always store variables accessed multiple times in a local variable. It speeds up execution (e.g. idata = data[i];).
  3. Avoid duck typing as far as possible (e.g. data[i].title != null). Check for the type of the variable first. It's slower, but the code is easier to understand and maintain. Try the typeOf function at the bottom of the post (e.g. typeOf(idata) === "Object").
  4. It's usually always better to use === instead of == and !== instead of != because they don't perform type coercion which might lead to unexpected results.
  5. Instead of creating multiple inline styles, create a single class .greyBackground { background-color: #EEEEEE; } and set the className of each leftCol paragraph to greyBackground.
  6. Avoid using document.write. It's slow, causes reflow of the document, and halts loading assets while the page is downloading. The best way to create dynamic content using JavaScript is to use the document.createDocumentFragment method as I'll explain below.
  7. It's always better to create nodes in JavaScript yourself. If you use a string in document.write or element.innerHTML then the browser parses the string and converts it into the nodes anyway. Thus using that method is slower.

This is how I would have written your JavaScript:

var data = [
    "Row Title 1",
    {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    },
    "Row Title 2",
    {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }
];

function typeOf(value) {
    if (value === null) {
        return "null";
    } else if (typeof value === "undefined") {
        return "undefined";
    } else {
        return Object.prototype.toString.call(value).slice(8, -1);
    }
}

var element;
var fragment = document.createDocumentFragment();
var idata;

for (var i = 0, l = data.length; l--; i++) {
    idata = data[i];
    if (typeOf(idata) === "Object") {
        element = document.createElement("p");
        element.className = "greyBackground";
        element.appendChild(document.createTextNode(idata.leftCol));
        fragment.appendChild(element);

        element = document.createElement("p");
        element.appendChild(document.createTextNode(idata.rightCol));
        fragment.appendChild(element);
    } else {
        element = document.createElement("b");
        element.appendChild(document.createTextNode(idata));
        fragment.appendChild(element);

        element = document.createElement("br");
        fragment.appendChild(element);
    }
}

document.body.appendChild(fragment);

Test my page and yours. In all probability mine will execute faster. If you have any doubts feel free to ask me. Cheers! =)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文