2016-09-22 30 views
0

腳本:如何計算在數組中的項目,如開發者控制檯

vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"]; 
vL2 = ["1", "1", "1", "2", "3", "1", "1", "2", "1", "1"]; 

for(var i = 0; i < vL1.length; i++){ 
    thing = vL1[i] + " " + vL2[i]; 
    console.log(thing); 
} 

當我檢查開發者控制檯,我看到以下內容:

(3) AB 1 
    AB 2 
    AB 3 
(2) CS 1 
    CS 2 
(2) ND 1 

如何修改劇本,所以我可以得到AB1出現的次數或CS1出現在我的代碼中用於其他功能?

我只想知道在vL1中代表的每個vL2的計數。將vL1聯繫起來很重要,因爲這會讓我識別vL2,因爲它不是唯一的。

+0

即在開發人員控制檯,並且不能在其他功能中使用。我怎樣才能在我的代碼中得到相同的結果放入一個數組或其他東西,因此它可以用於其他功能? – SearchForKnowledge

回答

1

您可以將計數存儲在一個對象中。此外,利用Array.prototype.reduce可以更簡單地與索引工作(例如,您不必處理遞增手動索引等):

vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"]; 
 
vL2 = ["1", "1", "1", "2", "3", "1", "1", "2", "1", "1"]; 
 

 
var counts = vL1.reduce(function(counts,vL1Element,index) { 
 
    //initialize this index if it isn't set 
 
    if(counts[vL1Element] == undefined) { 
 
    counts[vL1Element] = {}; 
 
    } 
 
    //set this count to 0 if it hasn't been set yet 
 
    if (counts[vL1Element][vL2[index]] == undefined) { 
 
    counts[vL1Element][vL2[index]] = 0; 
 
    } 
 
    counts[vL1Element][vL2[index]]++; 
 
    return counts; 
 
},{}); 
 
console.log(counts);

+0

謝謝。這正是我需要的。我怎麼能訪問,比方說'3'的'AB'計數? – SearchForKnowledge

+0

你可以使用counts.AB [3] ... –

+0

我希望這是有道理的:>對象{Test%20It%20Out:Object,Here%20It%20Comes:Object ...} 當我展開它時以下內容: >測試%20IT%20Out:對象 >這裏%20IT%20Comes:對象 當我展開讓我們說'這裏%20IT%20Comes'我看到以下內容: 2:3 5:15 10:2 11:29 我該如何訪問讓我們來說'Here%20It%20Comes'>'10' count,這應該給我'2'。 – SearchForKnowledge

1
var obj={}; 
function log(a){ 
if(obj[a]){ 
    obj[a]++; 
}else{ 
    obj[a]=0; 
} 
} 

然後執行:

log(thing); 

裏面的你的for循環,而不是:

console.log(obj); 

的OBJ現在包含: AB1:3; ....

+0

是否適合每個條目?我可以訪問它如何?謝謝。我傳遞給'a'的是什麼? – SearchForKnowledge

+0

@SearchForKnowledge:一個字符串,就像你用console.log所做的那樣 –

+0

我得到了'undefined'。 – SearchForKnowledge

2

你也可以做如下;

var vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"], 
 
    vL2 = ["1", "1", "1", "2", "3", "1", "1", "2", "1", "1"], 
 
result = vL1.reduce((p,c,i) => p[c] ? (p[c][vL2[i]] = p[c][vL2[i]] ? ++p[c][vL2[i]] 
 
                    : 1, p) 
 
            : (p[c] = {[vL2[i]]: 1}, p), {}); 
 
console.log(result);

+0

謝謝。我如何鑽取? – SearchForKnowledge

+1

@SearchForKnowledge基本上它是作爲回調傳遞給[reduce](https)的[ES6箭頭函數](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)的實現://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)而不是'for'迭代和[ternary](https://developer.mozilla.org/ tr/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)鏈而不是'if'和'else'。 – Redu

+0

謝謝。所以我只是好奇如何獲得AB> 3的計數?我會查看鏈接以獲得更好的說明。 – SearchForKnowledge