JavaScript-用旧语法替换循环

我有成功运行的此代码。


function maxChar() {  

      const charMap = {a:1, b:3, a:1}

      let max = 0

      let maxChar = ''


      for(let index in charMap) {

        if(max < charMap[index]){

          max = charMap[index]

          maxChar = index

        } 

      }


      return maxChar

    }


    console.log(maxChar())

它正在控制台b上返回,这是重复次数最多的字母。


但是我想对旧语法做同样的事情。


我将如何替换呢?


for(let index in charMap) {//....

和其余的代码


临摹微笑
浏览 195回答 3
3回答

繁星coding

如果要使用tradition for loop循环对象。您首先需要获取所有密钥,Object.keys(charMap)然后再遍历这些密钥。function maxChar() {&nbsp;&nbsp;&nbsp; &nbsp; const charMap = {a:1, b:3, a:1}&nbsp; &nbsp; let max = 0&nbsp; &nbsp; let maxChar = ''&nbsp; &nbsp; const charMapKeys = Object.keys(charMap)&nbsp; &nbsp; for(let i = 0; i < charMapKeys.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(max < charMap[charMapKeys[i]]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = charMap[charMapKeys[i]]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxChar = charMapKeys[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; return maxChar}console.log(maxChar())PS:但是建议您使用for &nbsp;... in循环遍历对象,因为它更干净并且从一开始就受到支持。

慕勒3428872

您可以在没有其他变量的情况下获得最大值。为了拥有符合ES5的代码,请将所有变量声明更改为var语句。function maxChar() {&nbsp; &nbsp; var charMap = { a: 1, b: 3, a: 1 },&nbsp; &nbsp; &nbsp; &nbsp; maxKey,&nbsp; &nbsp; &nbsp; &nbsp; key;&nbsp; &nbsp; for (key in charMap) {&nbsp; &nbsp; &nbsp; &nbsp; if (!maxKey || charMap[maxKey] < charMap[key]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxKey = key;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return key;}console.log(maxChar());

慕码人2483693

该for .. in自EcmaScript的第一版循环语法一直存在。唯一需要适应的是:let和const更改它们var。function maxChar() {&nbsp;&nbsp;&nbsp; var charMap = {a:1, b:3, a:1};&nbsp; var max = 0;&nbsp; var maxChar = '';&nbsp; for (var index in charMap) {&nbsp; &nbsp; if (max < charMap[index]) {&nbsp; &nbsp; &nbsp; max = charMap[index];&nbsp; &nbsp; &nbsp; maxChar = index;&nbsp; &nbsp; }&nbsp;&nbsp; }&nbsp; return maxChar}console.log(maxChar());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript