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

标签 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);             
});
<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>

我目前正在寻找一种将参数传递给函数而不实际将其添加到函数调用的解决方案。 在这种情况下,我想构建一个简单的 <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);             
});

对于有关此问题的任何提示、解决方案或提示,我将不胜感激。

最佳答案

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

$.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);             
});

关于javascript - 将参数传递给函数而不将其添加到函数调用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32461953/

相关文章:

javascript - 为什么被调用函数中的参数必须有其他 "names"并且与调用它的参数不同?

c - C 中未声明的参数

PHP SET函数中的默认参数作为静态变量

javascript - 删除超过 2 小时的 firebase 数据

JavaScript 正则表达式 : match all specific chars ignoring nested parentheses

javascript - 是否可以在函数内使用变量动态调用 Azure 函数的 Cosmos DB 输入绑定(bind)的 SQL 查询?

arrays - 如何在 Robo3T 中将结果从一个查询传递到另一个查询

javascript - Meteorjs - Meteor.call ('myMethod' )返回三个对象而不是一个数组?

javascript - 在javascript函数中切换传入变量 boolean 值

javascript - 程序运行后如何修复 undefined variable