Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 重画和回流上的这个函数在做什么?_Javascript_Html - Fatal编程技术网

Javascript 重画和回流上的这个函数在做什么?

Javascript 重画和回流上的这个函数在做什么?,javascript,html,Javascript,Html,JS代码旨在最小化所需的重画和回流次数。我对这个概念很陌生,所以我不确定函数在做什么……特别是for循环 (function() { var element, index, length, content = document.getElementById("content"), html = "", data = [{ id: 1, name: "

JS代码旨在最小化所需的重画和回流次数。我对这个概念很陌生,所以我不确定函数在做什么……特别是for循环

(function() { 
    var element, 
        index, 
        length, 
        content = document.getElementById("content"),
        html = "",
        data = [{ 
            id: 1, 
            name: "John", 
            color: "green" 
        }, { 
            id: 2, 
            name: "Sally", 
            color: "pink" 
        }, { 
            id: 3, 
            name: "Andrew", 
            color: "blue" 
        }, { 
            id: 4, 
            name: "Katie", 
            color: "purple" 
        }];

    for (index = 0; index < data.length; index++) {
        html +=
            '<li id="' + data[index].id + '" style="color: ' + data[index].color + '">' +
                '<strong>' + data[index].name + '</strong>' +
            '</li>';
    } 

    content.innerHTML = html;
 })();
(函数(){
var元素,
指数
长度,
content=document.getElementById(“content”),
html=“”,
数据=[{
id:1,
姓名:“约翰”,
颜色:“绿色”
}, { 
id:2,
姓名:“莎莉”,
颜色:“粉色”
}, { 
id:3,
姓名:“安德鲁”,
颜色:“蓝色”
}, { 
id:4,
姓名:“凯蒂”,
颜色:“紫色”
}];
对于(索引=0;索引”+
“”+数据[索引]。名称+”'+
“”;
} 
content.innerHTML=html;
})();

for循环的
只是将数组中每个元素的字符串串联起来。这样做的目的是将列表的所有HTML放在一个字符串中,然后将其放在DOM中一次,而不是每次通过循环都附加到HTML中。这更有效,因为HTML只需呈现一次,而不必多次呈现。

要查看输出,请执行以下操作:

(函数(){
var元素,
指数
长度,
content=document.getElementById(“content”),
html=“”,
数据=[{
id:1,
姓名:“约翰”,
颜色:“绿色”
}, { 
id:2,
姓名:“莎莉”,
颜色:“粉色”
}, { 
id:3,
姓名:“安德鲁”,
颜色:“蓝色”
}, { 
id:4,
姓名:“凯蒂”,
颜色:“紫色”
}];
对于(索引=0;索引”+
“”+数据[索引]。名称+”'+
“”;
} 
content.innerHTML=html;
})();

谢谢,这是非常深入的。