我试图理解这里使用 svg 制作的径向进度条的代码,但我无法理解以下部分中使用的 var forEach。 它是否是一些特殊定义的变量,因为如果我们将其替换为 temp 等其他变量,它就不起作用。还请解释传递给函数的参数的来源。
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}}
这是完整的代码: 帮助将不胜感激:)
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var con = "<div class='center'></div>";
$("body").prepend(con);
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttributeNS(null, 'width', '200px');
svg.setAttributeNS(null, 'height', '280px');
svg.setAttributeNS(null, 'class', 'progress');
svg.setAttributeNS(null, 'data-progress', '65');
$('.center').prepend(svg);
var path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttributeNS(null, 'class', 'fill');
path.setAttributeNS(null, 'd', 'M5,40a35,35 0 1,0 70,0a35,35 0 1,0 -70,0');
$("svg").prepend(path);
var spath = document.createElementNS("http://www.w3.org/2000/svg", "path");
spath.setAttributeNS(null, 'class', 'track');
spath.setAttributeNS(null, 'd', 'M5,40a35,35 0 1,0 70,0a35,35 0 1,0 -70,0');
$("svg").prepend(spath);
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}}
window.onload = function(){
var max = -219.99078369140625;
forEach(document.querySelectorAll('.progress'), function (index,value){
percent = value.getAttribute('data-progress');
value.querySelector('.fill').setAttribute('style',
'stroke-dashoffset: ' + ((100 - percent) / 100) * max);});}})
</script>
最佳答案
var forEach
这里我们定义一个变量来保存对函数的引用。
function(array, callback, scope)
该函数接受三个参数:
- array:我们可以迭代的数组。
- 回调:对函数的引用。
- 范围:将用于运行回调的范围(这定义了回调内部的“this”)。
for (var i = 0; i < array.length; i++)
只是一个for循环。
callback.call(scope, i, array[i])
call() 是 Function 类型的方法,它相当于调用函数,就像执行 callback() 一样,但还有一个额外的好处是让您可以在特定范围内运行该函数。即:
var f = function(){
console.log("Hi, " + this.name);
};
var scope1 = {name: "John"};
var scope2 = {name: "Peter"};
f.call(scope1);// logs Hi, John
f.call(scope2);// logs Hi, Peter
另外两个 call() 参数作为参数传递给函数。
希望能够澄清源参数的工作原理。
关于Javascript forEach 作为特殊变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184194/