簡體   English   中英

使用“ in”運算符編譯直方圖的正確方法是什么?

[英]What is the right way to use the “in” operator to compile a histogram?

我正在為數組實現直方圖函數,以便返回一個對象,該對象計算一個項目在該數組中出現的次數。 但是,每當我運行此代碼時,我都會收到一條錯誤消息,提示“ 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引起的問題,但我不知道是什么原因。 有任何想法嗎?

有兩件事: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;
  }, {});
}

演示

這是一個較短的版本,它不依賴於in的使用:

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

演示

in 運算符的問題在於它不僅在數組索引中搜索,而且還在數組對象的所有繼承屬性中搜索。

var ar = [];

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

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

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

暫無
暫無

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

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