javascript - JS数组方法调用问题 this.lastIndexOf

查看:82
本文介绍了javascript - JS数组方法调用问题 this.lastIndexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

> 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

这篇关于javascript - JS数组方法调用问题 this.lastIndexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆