Mat*_*hew 15 javascript arrays for-loop
我正在寻找一种从数组中删除重复值的简单方法.我想出了如何检测是否有重复,只是我不知道如何从值中"推"它.例如,如果您转到提供的链接,然后键入"abca" (在每个字母后按回车键/输入键) ..它将提醒"重复!"
但我还想弄清楚如何从textarea中删除该副本?
这是似乎无法正常工作的部分::
sort = sort.push(i);
textVal = sort;
return textVal;
Run Code Online (Sandbox Code Playgroud)
小智 51
为什么这么难,可以使用专门用于此类操作的javascript过滤功能更轻松地完成:
var arr = ["apple", "bannana", "orange", "apple", "orange"];
arr = arr.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
});
---------------------
Output: ["apple", "bannana", "orange"]
Run Code Online (Sandbox Code Playgroud)
基于 user2668376 解决方案,这将返回一个没有重复的新数组。
Array.prototype.removeDuplicates = function () {
return this.filter(function (item, index, self) {
return self.indexOf(item) == index;
});
};
Run Code Online (Sandbox Code Playgroud)
之后你可以这样做:
[1, 3, 3, 7].removeDuplicates();
Run Code Online (Sandbox Code Playgroud)
结果将是;[1, 3, 7].
| 归档时间: |
|
| 查看次数: |
64349 次 |
| 最近记录: |