我的任务是从字符串中按顺序接收唯一元素作为参数。我不明白这个函数uniqueElements如何返回['A','B','C','B']
。
var word = "AAAABBBBCCBB";
var uniqueElements = function(word) {
return [].filter.call(word, (function(elem,index) {
return word[index-1] !== elem
}));
}
uniqueElements(word);
//it should return ['A','B','C','B']
我检查并阅读了以下来源:
MDN Mozilla和 JS Blog但没有成功。
最佳答案
这里[].filter.call
的目的是对字符串应用filter
方法。天真地你会首先尝试这样做:
return word.filter(function(elem,index) {
return word[index-1] !== elem;
});
... - 如果 word
是一个数组 - 将返回其中满足条件 word[index-1] !== elem
的字符(这是 word[index-1] !== word[index]
的缩写),即每个字符与其前面的字符不同。
但是,filter
方法仅存在于从 Array
原型(prototype)继承的对象上,而字符串则不然。
但是,filter
本身可以处理类似数组的对象,即具有长度
并且可能具有数值属性的对象。要在没有真正的 Array
对象的情况下调用 filter
,您可以在该函数上使用 call
,然后提供上下文(即类似数组的对象) )作为第一个参数。其他参数保持不变。因此,您首先需要知道在哪里可以找到 filter
方法...它位于 Array.prototype
上,因此您可以像这样引用它:
Array.prototype.filter
但是由于所有数组都可以访问此方法,因此仅采用空数组并引用其 filter
方法会更短:
[].filter
两者都可以。现在您必须对其执行 call
方法,并提供您想要迭代的类数组对象:
[].filter.call(words, ...)
其余的就像处理真正的数组一样:您提供回调函数:
return [].filter.call(word, function(elem,index) {
return word[index-1] !== elem
});
返回值不再是字符串。它——就像filter
总是返回——一个数组:一个真实数组——它是由filter
方法创建的。
ES6方式:
在 ES6 中,你可以用一种更易读的方式来编写它,因为现在有 Array.from 方法,它可以将类似数组的对象转换为真正的数组。然后您可以继续使用 filter
方法:
return Array.from(word).filter(function(elem,index) {
return word[index-1] !== elem
});
扩展运算符是 ES6 提供的另一种选择:
return [...word].filter(function(elem,index) {
return word[index-1] !== elem
});
关于javascript - 谁能帮忙解释一下这个JavaScript算法 [].filter.call(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40531611/