将参数传递给函数而不将其添加到函数调用中

时间:2015-09-08 15:41:21

标签: javascript function arguments default

我尝试了你的解决方案,它似乎在堆栈溢出"代码运行环境"内工作正常。 我可能需要将它与原始代码进行比较。



$.getJSON("https://teamtreehouse.com/chalkers.json", function(result){

    var buildHtml = ""; 

    function buildLi(language){
        buildHtml += "<li>" + "<h4> language </h4> | <span>" + result.points[language] + "</span></li>";
    }

    buildHtml += "<ul>";
    buildLi("HTML");
    buildLi("CSS");
    buildLi("JavaScript");
    buildLi("PHP");
    buildHtml += "</ul>";

    $(".skill-ul-container").append(buildHtml);             
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>The Score</h1>
<div class="skill-ul-container"></div>
&#13;
&#13;
&#13;

我目前正在寻找一种解决方案,可以将参数传递给函数,而无需将其实际添加到函数调用中。 在这种情况下,我想构建一个简单的<ul>列表,其中<li>项从json文件中获取其内容。 如您所见,我反复将resultbuildHtml包含在函数调用中。但我想我不必这样做,对吧?有没有办法将它们默认包含在函数调用中? (因为它们在函数调用期间没有改变)

$.getJSON("that/nice/json/file/that/stores/my/score.json", function(result){

    var buildHtml = ""; 

    function buildLi(language, result, buildHtml){
        buildHtml += "<li>" + "<h4> language </h4> | <span>" + result.points[language] + "</span></li>"; //builds <li> that contains the programming language title and a number that is stored in result.points[language]
        return(buildHtml);
    }

    buildHtml += "<ul>";
    buildHtml = buildLi("HTML", result, buildHtml); //i want to get rid of "result and buildHtml" because these values are not supposed to be changed during the function call.
    buildHtml = buildLi("CSS", result, buildHtml);
    buildHtml = buildLi("JavaScript", result, buildHtml);
    buildHtml = buildLi("PHP", result, buildHtml);
    buildHtml += "</ul>";
    $(".skill-ul-container").append(buildHtml);             
});

我感谢您提供有关此问题的任何提示,解决方案或提示。

3 个答案:

答案 0 :(得分:1)

如果在此回调函数中定义buildLi,则不需要包含这两个参数,因为两个变量都在函数的scope中,您可以毫无问题地使用它们

答案 1 :(得分:1)

你可以在函数声明和所有调用中将它们作为参数删除,因为这些变量都在整个代码段的范围内......

$.getJSON("that/nice/json/file/that/stores/my/score.json", function(result){

    var buildHtml = ""; 

    function buildLi(language){
        buildHtml += "<li>" + "<h4> language </h4> | <span>" + result.points[language] + "</span></li>";
    }

    buildHtml += "<ul>";
    buildLi("HTML");
    buildLi("CSS");
    buildLi("JavaScript");
    buildLi("PHP");
    buildHtml += "</ul>";

    $(".skill-ul-container").append(buildHtml);             
});

答案 2 :(得分:0)

除了将这两个参数作为全局变量访问之外,您还可以使用bind函数来创建函数的新版本并修复分配给this关键字的值以及之前的任意数量的参数调用新函数时提供的任何内容。