如何修复JSLint报错:Expected an identifier and instead saw '0'
修复JSLint报错:Expected an identifier and instead saw '0'
问题原因
JSLint对对象属性命名有严格规范,不允许使用未加引号的数字作为属性名。你代码中playerVarsList对象的0、1属性未加引号,违反了JSLint的检查规则,因此触发报错。
修复方案
有两种可行的修复方式:
方式一:给数字属性名添加引号
给对象中以数字开头的属性名加上双引号,让JSLint认可该属性名的合法性:
function onYouTubeIframeAPIReady() { let playerVarsList = { "0": { playerVars: { playlist: "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g" } }, "1": { playerVars: { listType: "playlist", list: "PLYeOyMz9C9kYmnPHfw5-ItOxYBiMG4amq" } } } //to add the player to all the play buttons const totalP = document.querySelectorAll('[data-container="play1"]').length; //looping over all the play buttons and adding player to that for (let i = 0; i < totalP; i++) { players.add(".playSingle" + i, (playerVarsList[i] || {})); } players.add(".playInitial", {}); }
方式二:改用数组存储(更推荐)
由于你是通过数字索引访问这些配置项,直接使用数组替代对象更符合JavaScript的语义,数组天然支持数字索引,且无需额外修改访问逻辑:
function onYouTubeIframeAPIReady() { let playerVarsList = [ { playerVars: { playlist: "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g" } }, { playerVars: { listType: "playlist", list: "PLYeOyMz9C9kYmnPHfw5-ItOxYBiMG4amq" } } ] //to add the player to all the play buttons const totalP = document.querySelectorAll('[data-container="play1"]').length; //looping over all the play buttons and adding player to that for (let i = 0; i < totalP; i++) { players.add(".playSingle" + i, (playerVarsList[i] || {})); } players.add(".playInitial", {}); }
验证
修改后JSLint即可正常完成代码检查,同时代码原有功能不受任何影响。
内容的提问来源于stack exchange,提问作者user17631451
相关产品推荐
相关产品推荐

