猿问

JS 为各种相似的文件返回单一文件类型(例如 'mp4' || 'm4v' = 'MOV')

我有一个 populateTable 函数,并且尝试将从 JSON 文件读取的几种不同文件类型组合成一种显示类型。在本例中,将 mp4 和 m4v 转换为 MOV — 我没有收到任何错误,但表中的所有内容都未定义。


function populateTable() {

    

    function setGenericType(type) {

        if(type == 'mp4' || type == 'm4v')  {

            return 'MOV'

        }

    }


    for (const d of data) {

        $("#contents").append(`<tr>

            <td>${d.title}</td>

            <td>${d.year}</td>

            <td>${setGenericType(d)}</td>

          </tr>`)   

    }

}

有任何想法吗?data.js 中的 JSON 示例:


{

    "title":"Arc Transition",

    "year":2016,

    "type":"mp4"

}


aluckdog
浏览 125回答 1
1回答

蓝山帝景

您将整个数据对象传递到setGenericType函数中,但将参数与字符串进行比较,因此它们永远不会匹配。如果类型不匹配,该函数将返回undefined。因此,要么将函数的参数视为传递给它的对象function setGenericType(d) {&nbsp; if(d.type == 'mp4' || d.type == 'm4v')&nbsp; {&nbsp; &nbsp; return 'MOV'&nbsp; }}或者只是将对象的类型传递给函数并保持函数不变for (const d of data) {&nbsp; $("#contents").append(`<tr>&nbsp; &nbsp; <td>${d.title}</td>&nbsp; &nbsp; <td>${d.year}</td>&nbsp; &nbsp; <td>${setGenericType(d.type)}</td>&nbsp; &nbsp;</tr>`)&nbsp; &nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答