题目:
请给Array本地对象增加一个原型方法,它用于删除数组条目中重复的条目(可能有多个),返回值是一个包含被删除的重复条目的新数组。
问题:
Array.prototype.distinct = function() {
var temp = this.filter(function(item, index){
return this.lastIndexOf(item)===index;
})
return temp;
}
console.log(['a', 'b', 'c', 'd', 'b', 'a', 'a', 'e'].distinct());
报错:
"TypeError: this.lastIndexOf is not a function
at fidacecewu.js:3:17
at Array.filter (native)
at Array.distinct (fidacecewu.js:2:21)
at fidacecewu.js:20:79
at https://static.jsbin.com/js/prod/runner-3.41.9.min.js:1:13926
at https://static.jsbin.com/js/prod/runner-3.41.9.min.js:1:10855"
尝试解决:
//为什么这里就可以?没有报错
Array.prototype.distinct = function() {
var arr = this;
var temp = arr.filter(function(item, index){
return arr.lastIndexOf(item)!==index;
})
return temp;
}
//参照
function dele(arr){
var temp = arr.filter(function(item, index){
return arr.lastIndexOf(item)!==index;
})
return temp;
}
console.log( dele(['a', 'b', 'c', 'd', 'b', 'a', 'a', 'e']) );//["a", "b", "a"]
console.log(['a', 'b', 'c', 'd', 'b', 'a', 'a', 'e'].distinct());//
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
理解箭头函数,还有this