...

View Full Version : Array Help



whteout
07-06-2011, 11:09 PM
OK so I am trying to put together a function that takes an array and then takes the square root of each number in old array and writes to the screen the new array of squared numbers. Not looking for answer, just what I need to do for the logic in the for statement.

siberia-man
07-06-2011, 11:33 PM
Firefox and other Gecko-based browsers have the Array.prototype.map method implemented. So usage is very simple:


var a = [1, 2, 3, 4, 5];
var b = a.map(function(v)
{
return Math.sqrt(v);
});

alert(a);
alert(b);


There is very simple emulation for Internet Explorer. Usage is the same as shown above:


Array.prototype.map = function(fun)
{
var result = [];
for (var i = 0, L = this.length; i < L; i++) {
result.push(fun(this[i]));
}
return result;
};

whteout
07-07-2011, 12:36 PM
Is there a more elementary way of writing this? This would be something that an advanced user would use.

bullant
07-07-2011, 01:57 PM
Is there a more elementary way of writing this?

yep there is.

Post the code you have so far and we can try to help you get it working.

Kor
07-08-2011, 10:54 AM
- send the array (let's call it old array) as an argument to a function

within that function:
- create a blank new array
- loop trough the elements of the old array
- rise each element to its square value
- assign the square values as the elements of the new array
- return the new array

whteout
07-08-2011, 12:49 PM
Got it

Thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum