仅返回数组数据,而不返回使用 Array.prototype 的函数本身

Return only array data without return the function itself using Array.prototype

本文关键字:返回 prototype Array 函数 数据 数组      更新时间:2023-09-26

我正在编写一个函数来执行一些数据过滤。我写这个:

Array.prototype.keyFilter = function ()
{
    var dta = this;
    for ( i in dta )
    {
        console.log( dta[i] );
    };
};
console.log( ['green','yellow','blue'].keyFilter('type') );

回报是:

green
yellow
blue
function ()
    {
        var dta = this;
        for ( i in dta )
        {
            console.log( dta[i] );
        };
    }
undefined

好的,我得到了数组数据...加上函数本身和一个"未定义"。如何使用 Array.prototype 仅获取数组数据?

感谢您的任何帮助。

您正在使用 for...in ,它迭代对象的可枚举属性,包括您添加到原型的函数。这显然不是你打算迭代数组的方式。

如果要遍历数组,则应使用简单的for循环,并从0计数到length - 1...

for (var i = 0; i < this.length; ++i) {
  console.log(this[i]);
}

或者,使用 forEach

this.forEach(function (i) {
  console.log(i);
});

"未定义"部分是记录函数返回值的外部console.log(...),这是undefined,因为您不返回任何内容。