簡體   English   中英

JavaScript在for循環中找到匹配的值

[英]JavaScript finding matching values in a for loop

數組按升序排序,我想獲取由冒號分隔的匹配值。

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

 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 

 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]) } 

我不太確定您要達到什么目標。 我希望這能滿足您的需求。

 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)}"`)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM