仅返回数组数据,而不返回使用 Array.prototype 的函数本身
Return only array data without return the function itself using Array.prototype
我正在编写一个函数来执行一些数据过滤。我写这个:
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
,因为您不返回任何内容。
相关文章:
- 如何在返回单个对象时递归使用 Array.prototype.find()
- 如果 Array.prototype.map() 没有返回,它是否被正确使用
- Prototype.js 1.7:将collect与显式函数一起使用会返回与内联函数不同的结果,原因是什么
- 为什么 String.prototype.split 返回完整的字符串
- 在 Function.prototype.method 中返回它有什么作用
- 为什么 Object.prototype.toString 返回 [object Object]
- 仅返回数组数据,而不返回使用 Array.prototype 的函数本身
- 从 Array.prototype 方法返回数组的值
- string.prototype.search('$') 在每个字符串上返回正 int
- 为什么 Object.keys(Array.prototype) 返回空数组
- Array.prototype.some() 是否返回文字?如果是这样,这段代码是什么意思
- JavaScript:Object.prototype.toString(new Number(5)) 似乎返回了一个错
- 为什么Array.prototype.some返回布尔值
- 为什么 Array.prototype.each 在空数组上返回 true
- 如何创建一个JavaScript构造函数,将自定义字符串返回给Object.prototype.toString()
- 为什么prototype函数在javascript中没有返回值
- 在Javascript引擎中,function. prototype. tostring不返回该函数的源代码
- prototype返回[function]而不是Array
- 我的工厂应该返回一个带有辅助方法的对象,还是应该使用prototype
- 无法在对象内返回对象.与string.prototype.replace方法不匹配的每个循环的关键字