javascript - JS数组方法调用问题 this.lastIndexOf
天蓬老师
天蓬老师 2017-04-11 13:10:18
[JavaScript讨论组]

题目:
请给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());//
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(2)
迷茫
> Array.prototype.distinct = function() {
...     var temp = this.filter( (item, index) => {
..... return this.lastIndexOf(item)===index;
.....   })
...   return temp;
... }
[Function]
> console.log(['a', 'b', 'c', 'd', 'b', 'a', 'a', 'e'].distinct());
[ 'c', 'd', 'b', 'a', 'e' ]

理解箭头函数,还有this

怪我咯

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号