Quick question. I was reading this book art/science of javascript and it defines its own custom filter method:
Code:
if (!Array.prototype.filter) {
Array.prototype.filter = function(func, scope) {
scope = scope || this;
var list = [];
for (var i = 0, l = this.length; i < l; i++)
if (func.call(scope, this[i], i, this)) list.push(this[i]);
return list;
}
}
I honestly don't understand this line right here "if (func.call(scope, this[i], i, this)) list.push(this[i]); " and what contribtues to that is that the book doesn't provide an example of the filter method being used. So I was wondering if anyone can provide a practical example of how to use this method.
I found another similar example, but notice how the call is sending for arguments: fun.call(thisp, this[i], i, this);
Yet the function (which is invoked by call()) is only receiving three arguments:
printBr(element, index, array)
How is this possible?
Also, why would we be passing the second index of the array right here: var thisp = arguments[1];
I don't see the point of that.
Code:
<html>
<head>
<title>JavaScript Array forEach Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
function printBr(element, index, array) {
document.write("<br />[" + index + "] is " + element );
}
[12, 5, 8, 130, 44].forEach(printBr);
</script>
</body>
</html>
Last edited by johnmerlino; 06-14-2010 at 06:42 PM..
i = to the index number
this[i] = equal to the integer or DOM element
this = equal to the array
pthis = equal to a specific integer or DOM element in array depending on what we passed from the arguments method - arguments[1] will pass the second index value.
thisp is the object that this inside fun will point to. this[i] is the i(th) Array element/item
if you don’t declare the thisp parameter in the function call (it is commented out in the example), you have to get it another way, that is by using the (internal) variable arguments holding the parameters passed to the function.
__________________
please post your code wrapped in [CODE] [/CODE] tags
Last edited by Dormilich; 06-17-2010 at 07:28 AM..