【问题标题】:JavaScript finding matching values in a for loopJavaScript 在 for 循环中查找匹配值
【发布时间】:2017-09-28 15:01:47
【问题描述】:

数组按升序排序,我想得到匹配的值,用冒号分隔。

var array = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5];
var text = "";

for(var i = 0; i < array.length - 1; i++) {
    if(array[0] == array[0 + 1]) {
         text = array[0] + ":" + array[0 + 1]; // 1:1
    }
}

这个 for 循环只检查两个匹配的值。如何检查所有匹配值的数量?

所以对于 1,文本将是 1:1
对于 2,文本将为 2:2:2
对于 5,文本将为 5:5:5:5

【问题讨论】:

  • 你需要嵌套一个循环
  • 我不太明白你想要达到的目标。为什么将所有内容都存储在同一个文本变量中?如果您只想将数组打印为文本,则有更简单的方法。如果您想存储每个数字文本,例如在数组中,这听起来像是 Array.reduce() 作业

标签: javascript arrays loops sorting matching


【解决方案1】:

var array = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5]
var text = ''

for(var i = 0; i < array.length; i++) {
    if (array[i] == array[i + 1]) {
         // always add a : suffix
         text += array[i] + ':'; 
    } else {
         // replace the last character with the last value and a new line
         text = text.replace(/.$/, ':' + array[i] + '\n')
    }
}

console.log(text.trim()) // trim the trailing whitespace 

【讨论】:

    【解决方案2】:

    var array = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5],
    arrayLength = array.length,
    text = {};
    
    
    for(var i = 0; i < arrayLength; i++) {
        if(!text.hasOwnProperty(array[i])){
          text[array[i]] = []
          for(var e = 0; e < arrayLength; e++){
              if(array[i] == array[e]){
                text[array[i]].push(array[i])
              }
          }
          text[array[i]] = text[array[i]].join(':')
        }
    }
    
    
    
    //and now you can access to every string by text[number]
    
    for(var key in text){
        console.log(text[key])
    }

    【讨论】:

      【解决方案3】:

      我不太确定您要达到的目标。我希望这能满足您的需求。

      const 
        input = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5],
        // Based on the input create a set, each value will appear only once in 
        // the set.
        uniqueIds = new Set(input),
        result = [];
      
      // Iterate over all the unique values of the array.
      uniqueIds.forEach(id => {
        // Add the text for the current value to result array.
        result.push(
          // Filter the array, take only the items that match the current value. This
          // will result in a new array that can be joined using a ":" as a
          // separator character.
          input.filter(value => value === id).join(':')
        );
      });
      
      
      // Or on a single line:
      // uniqueIds.forEach(id => result.push(input.filter(value => value === id).join(':')));
      
      console.log(result);

      如果您想根据您提供的输入获取字符串,也许这样会更好:

      const 
        input = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5],
        textWrapper = (function() {
          let
            array = null,
            cache = {};
            
          function getText(number) {
            if (cache[number] !== undefined) {
              console.log(`Cache hit for number ${number}`);
              return cache[number];
            }
            
            const
              text = array.filter(item => item === number).join(':');
            cache[number] = text;
            
            return text;
          }
            
          function setArray(value) {
            array = value;
            cache = {};
          }
          
          return {
            getText,
            setArray
          }
        })();
        
      textWrapper.setArray(input);
      
      const
        values = [1, 3, 5, 5];
        
      values.forEach(value => console.log(`Text for ${value} is "${textWrapper.getText(value)}"`));

      【讨论】:

        猜你喜欢
        • 2021-02-02
        • 2012-03-27
        • 2020-04-06
        • 2011-04-28
        • 2015-10-05
        • 2021-01-12
        • 2019-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多