View Single Post
Old 01-04-2013, 09:31 PM   PM User | #1
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,765
Thanks: 29
Thanked 453 Times in 447 Posts
jmrker will become famous soon enough
Question filter() function question

I'm trying to understand the filter function and have run into a problem with my first test.

Why does the function seem to add 1 to each element of the original array
but returns one less element in the new array?

Code:
<!DOCTYPE HTML>
<html>
<head>
<title> Untitled </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

function addOne(element, index, array) { return (element++); }
var Aarr = [0,1,2,3,4,5,6,7,8,9];
var Barr = Aarr.filter(addOne);
alert('Orig: \n'+Aarr+'\n\nadd 1: \n'+Barr);

/*
// From: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
function isBigEnough(element, index, array) { return (element >= 10); }
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
alert(filtered);    // filtered is [12, 130, 44] 
*/

</script>

</head>
<body>

</body>
</html>
The commented out test (isButEnough) seems to work as advertised.
jmrker is offline   Reply With Quote