![](/img/trans.png)
[英]What is the right way for using ternary operator inside string templates?
[英]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.