I try to add function to the object. Why does't it work? The result is undefined. Please help.
<html>
<body>
<script>
var calc = function(){
this.num1 = 5,
this.num2 = 5,
compute = function( ) {
this.result = this.num1 * this.num2;
}
};
var myObj =[];
for(var i=0; i<5; i++){myObj.push(new calc())};
//calc.compute();
document.write(myObj.compute);
</script>
</body>
</html>
There are a couple of immediate issues. First, constructors should be written in the style function Calc(args) to distinguish them from other functions, and to also solve scope/context issues.
Second, your method should be this.compute.
Third, while adding the numbers to a result variable is fine, from the rest of your code you look like you want to return something from compute but you're not.
Finally, why do you want to create five identical objects? I've corrected but also updated your code a little bit below to show you what I mean.
function Calc(first, second) {
// assign the arguments to num1 and num2
this.num1 = first;
this.num2 = second;
this.compute = function() {
// we return the result rather than assigning it
return this.num1 * this.num2;
}
};
var myObj = [];
// here we use i and 5 as the new object parameters
for (var i = 0; i < 5; i++) {
myObj.push(new Calc(i, 5));
};
for (var i = 0; i < 5; i++) {
console.log(myObj[i].compute()); // 0, 5, 10, 15, 20
};
DEMO
Now, as deceze suggests, separating out the method and defining it on the prototype is also a good idea, so you'd end up with the following code:
function Calc(first, second) {
this.num1 = first;
this.num2 = second;
};
Calc.prototype.compute = function() {
return this.num1 * this.num2;
}
DEMO
Try associating the function with the object with this keyword. Currently compute function is not associated with the object.
Also you need to return the result and accessing object by index
So correct one will be
var calc = function() {
this.num1 = 5,
this.num2 = 5,
this.compute = function() {
this.result = this.num1 * this.num2;
return this.result;
}
};
var myObj = [];
for (var i = 0; i < 5; i++) {
myObj.push(new calc())
};
//calc.compute();
document.write(myObj[0].compute());
Issues:
Missing parenthesis document.write(myObj.compute);. It should be document.write(myObj.compute());.
myObj is an array of objects of type Calc. So you will need index to access any property of object. myObj[0].compute().
Missing return statement in compute function. You are assigning value to this.results but not returning anything. I have removed results and have added return statement.
Following code represents the same:
var calc = function() {
// Store current context
var self = this;
self.num1 = 5,
self.num2 = 5,
compute = function() {
return self.num1 * self.num2;;
}
// public properties...
return {
compute: compute
}
};
var myObj = [];
for (var i = 0; i < 5; i++) {
myObj.push(new calc())
};
//calc.compute();
document.write(myObj[0].compute());
Related
I'm trying to store a value from a parameter to an array. Unfortunately, when I'm trying to push a value, it also changed the former value. So in the end, they all have same value but it shouldn't.
For example: I push "1". It store, but when I push "2", it replaced the "1"
Here is my code:
function Add(num) {
var numArr = [];
var count= 10;
for (var i = 0; i < count; i++) {
numArr.push(num);
}
console.log(numArr);
}
Make the array global, when it is inside the function, whenever the function is called a new array is created. when array is global this problem does not arises
var numArr = [];
function Add(num) {
var count = 10;
for (var i = 0; i < count; i++) {
numArr.push(num);
}
console.log(numArr);
}
Add(11)
Add(112)
The reason why the previous value is replaced is that with each function call you declare your array all over again, with no values in it var numArr = []. Move this definition outside this function and it should be just fine
var numArr = [];
const Add = (num) => {
var count= num;
for (let i = 0; i < count; i++) {
numArr.push(num);
}
return numArr
}
console.log(Add(10))
The problem is because you instantiate the array in every iteration of the loop. The simple fix is to pass the array in to the Add() function.
function Add(arr, num) {
var count = 10;
for (var i = 0; i < count; i++) {
arr.push(num);
}
}
var numArr = [];
Add(numArr, 999);
console.log(numArr);
You could alternatively declare the array outside of the function, but this ties the function logic to external variables which makes the point of the function entirely moot.
Also note that the function itself can be replaced with the Array.fill() method which does exactly the same thing, but is unsupported in IE:
var arr = new Array(10);
arr.fill(999);
console.log(arr);
The problem is you create new array when push new value.you can create global array and push value on it.
<script>
_glb_arr=[];
$(document).ready(function (){
Add(1);
Add(3);
console.log(_glb_arr);
});
function Add(val){
_glb_arr.push(val);
}
</script>
var mult = (function(){
var cache = {};
var calculate = function(){
var a = 1;
for(var i = 0, l = arguments.length; i < l; i++){
a = a * arguments[i];
}
return a;
}
return function(){
return calculate(arguments);
}
})();
console.log(mult(1, 2));
Above is my code, I expect the mult function will give me value 2, but instead it outputs NaN. I changed the line calculate(arguments) to caculate.apply(null, arguments) and it worked. I don't know why the old code doesn't work? Why do I need to use apply in this case? What does null represent here?
Your calculate function wants separate arguments, but you passed in an array1. Using .apply spreads the content of the array for you.
1 Technically an array-like arguments object that does not inherit from Array.
Well, I have to create an object that represents an polynom af any size:
var polynom = function() {
//code ...
};
p1 = polynom(1,6,3,4); // 1x^6 + 3x^4
p2 = polynom(3,5,2,1,7,3); // 3x^5 + 2x^1 + 7x^3
what I want to do is write a method that return an array with all these arguments. I read a little about this.arguments, so I write something like that:
var polynom = function() {
getArguments = function() {
array = [];
for(var i = 0; i < this.arguments.size; i++) array.push(this.arguments[i]);
return array;
}
};
const p1 = new polynom(3,2);
console.log(p1.getArguments());
and I get this message
TypeError: Cannot read property 'getArguments' of undefined
at eval:14:16
at eval
at new Promise
I'm new at javascript so sorry if there's something wrong, but I would appreciate some help to write this method.
What you are looking for is Rest arguments.
var polynom = function(...args) {
this.getArguments = function() {
var array = [];
for(var i = 0; i < args.length; i++) {array.push(args[i]);};
return array;
}
};
const p1 = new polynom(3,2);
console.log(p1.getArguments());
I have like 40 different arrays and I want to find the average value of each of them.
In order to do it with each one, I have this code:
var SumArray1 = 0;
var avgArray1 = 0;
$.each(array1,function() {
SumArray1 += this;
avgArray1 = (SumArray1)/(array1.length);
});
But as I have those 40 arrays, I was trying to look for a way to make that function abstract, but I don't know how to introduce parameters for a function using $.each and I don't think having forty functions would be the right thing to do...
Thanks!
Your implementation calculates the average each time, but it only gets a correct value the last time. This is not necesary.
Also, there's no need to use $.each, which forces you to use an additional closure (my previous statement about waiting was wrong, since $.each is synchronous).
The following is simpler:
function avgArray(array) {
var i,l,s = 0;
for (i=0,l=array.length; i<l; i++) s+= array[i];
return s/l;
}
Add this code:
Array.prototype.average = function() {
var s = 0;
for(var i = 0; i < this.length; ++i) {
s += this[i];
}
return s/this.length;
}
Then at any point you can do something like
var myArray = [1,2,3,4];
var calculatedAverage = myArray.average(); // This will equal 2.5
Arrays have a built in reduce function, if you like short one-liners you can also do this:
var arr = [1,2,3,4];
function sum(x,y){
return x + y;
}
var total = arr.reduce(sum); // total -> 10
// This also works
var total = arr.reduce( function(x,y) { return (x + y); } );
var avg = ( total / arr.length );
Reduce is a higher-order function that 'reduces' an sequence into a single value.
Here is the execution flow of reduce.
var temp = sum( arr[0], arr[1] );
temp = sum( temp, arr[2] );
temp = sum( temp, arr[3] );
return temp;
Stealing Andrew Shepherd answer for adding new functions to the Array data structure.
Array.prototype.sum = function() { return this.reduce( function(x,y) { return (x+y); } )};
Array.prototype.avg = function() { return (this.sum() / this.length) };
How do I write a function in JavaScript that receives an array and a function(convertFunc). The function calls convertFunc for every element of the array.
The element should be accessed via the this keyword.
The function should return an array of the return values of the convertFunc calls?
e.g.
function(array, convertFunc() { // array=[1,2,3]
return this+10;
}
Should return [11,12,13]
Thanks
Create the function, e.g. function map(arr, convertFunc) {
Iterate over all elements of the array arr.
Tip: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call
Return an array containing all results from the function calls.
}
Figure the exact details out by yourself, good luck :)
array.map(callback[, thisObject]); might fit for you.
Example:
var nums = [1,2,3];
function FuncName(x)
{
return x+10;
}
var result = nums.map(FuncName); //[11,12,13]
Try this if you are looking for extending the Array object
Array.prototype.convertFunc = function() {
var arr = this, i; // As you want array is access using the this keyword.
for(i = 0; i<arr.length; i++)
{
arr[i] = arr[i] + 10;
}
return arr;
}
var myArray = [1,2,3];
// Call like this
myArray.convertFunc();
Fiddle here http://jsfiddle.net/PYxzj/
Update
And to answer your question try this
// Pass your array and a function as parameter
function arrayModify(array, convertFunc)
{
return array.convertFunc();
}
// This function iterates your array and adds 10 to each element.
var arrayAddFunction = function() {
var arr = this, i;
for(i = 0; i<arr.length; i++)
{
arr[i] = arr[i] + 10;
}
return arr;
}
// Extending the array object
Array.prototype.convertFunc = arrayAddFunction;
var aa = [1,2,3];
// As you want send your array and a function as parameters to another function
alert(arrayModify(aa,arrayAddFunction)); // -> [11, 12, 13]
Fiddle here http://jsfiddle.net/qzB4e/
var myFunc = function(fn) { // array=[1,2,3]
return fn(this);
};
myFunc.call(arr,function convertFunc(){
return this+10;
});
But, to solve your exact problem:
var arr = [1,2,3], addTen = function(){
for (var l=this.length;l--;) this[l] += 10;
};
addTen.call(arr);