2016-04-21 21 views
0

我正在爲數組實現一個直方圖函數,以便返回一個對象,該對象計算一個項目在該數組中出現的次數。然而,無論何時運行此代碼,我都會遇到一條錯誤消息,表明「in」運算符不能用於在對象內進行搜索。使用「in」運算符編譯直方圖的正確方法是什麼?

var histogram = function(collection) { 
    collection.reduce(function(combine, item){ 
    if(item in combine){ 
    combine[item]++; 
    } else{ 
    combine[item] = 1; 
    } 
    }, {}); 
} 
var arr = "racecar".split(""); 
console.log(hist(arr)); 

我猜這裏的問題是由in還是reduce引起的,但我找不出它是哪一個。有任何想法嗎?

+0

您可能想要避免[in operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in),它可能不會達到您的預期。 –

回答

0

幾件事:1)hist不是函數名,2)你沒有從函數返回任何東西。我不確定如果你沒有正確地調用這個函數,並且控制檯日誌會警告你,你會如何得到這個錯誤。

var histogram = function(collection) { 
    return collection.reduce(function(combine, item) { 
    if (item in combine) { 
     combine[item]++; 
    } else { 
     combine[item] = 1; 
    } 
    return combine; 
    }, {}); 
} 

DEMO

下面是一個不依賴於使用的in一個較短的版本:

var histogram = function(collection) { 
    return collection.reduce(function (combine, item) { 
    combine[item] = (combine[item] || 0) + 1; 
    return combine; 
    }, {}); 
} 

DEMO

+1

謝謝安迪!不能相信我放棄了兩個返回語句,修復了它。我想我被一條錯誤信息拋棄了,這引起了我錯誤的注意。 –

0

的問題inoperator的是,它不僅搜索在數組索引中,但也在Array對象的所有繼承屬性中。

var ar = []; 

'toString' in ar; // prints true 
'length' in ar; // prints true 

當在不正確的上下文中使用(查找數組中的索引)時,它可能會引入潛在的問題,以後難以調試。

在你的情況下,最好是使用Array.prototype.indexOf()Array.prototype.includes()(來自ES6)。

相關問題