如何写一个for循环来查找和替换?

问题描述 投票:0回答:2

我在编写函数来遍历列表、查找并替换匹配时遇到问题。这是我到目前为止所拥有的:

function lookupTests(tests) {
    for (var i = 0; i < tests.length; i++) { 
        const currentTest = tests[i];
        // check if the current fruit exists in the lookup table
        if (translation[currentTest]) {
            // replace the current fruit with its value from the lookup table 
            tests[i] = translation[currentTest]; 
        }
    } 
};
    
var translation = {
    'AMIK':'AMIK',
    'GROU':'GPW',
    'AASC':'ABW',
    'ICOO':'ABW',
    'HPLC':'HBEW',
    'SICK':'SICW',
};
var tests = lookupTests([AASC,GROU]);

我得到的错误信息是

DETAILS:    TypeError: Cannot read property "AASC" from undefined
javascript loops mirth
2个回答
0
投票

在工作之前看到答案,我也写了一些东西,我想分享这个解决方案:使用 Object.entries(),这样你就可以更好地控制条目的键和值。

function lookupTests(tests) {
  // Iterate the translations: 
  // Keys would be 'AMIK', 'GROU' ... e.g. the first part
  // Values would be 'AMIK', 'GPW' ... e.g. the second part
  Object.entries(translation).forEach(([translationKey, translationValue]) => {
  // Iterate the tests:
  // Keys would be 0, 1, 2, 3 ...
  // Values would be the array you provide e.g. ['AASC', 'GROU']
    Object.entries(tests).forEach(([testsKey, testsValue]) => {
      if (translationKey !== testsValue) return
      tests[testsKey] = translationValue
    })
  })
  return tests
}

var translation = {
    'AMIK':'AMIK',
    'GROU':'GPW',
    'AASC':'ABW',
    'ICOO':'ABW',
    'HPLC':'HBEW',
    'SICK':'SICW',
};

var tests = lookupTests(['AASC', 'GROU']);
console.log(tests)  returns  ['ABW', 'GPW']

希望这有帮助!


0
投票

代码按预期运行,您只需要在函数末尾添加一个

return
即可。

© www.soinside.com 2019 - 2024. All rights reserved.