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>
Related
I am trying to create an array of objects. One object property is a function, which I want to change value of depending on which number in the array the object is.
When I try to use the 'i' value from the for loop, this is not being maintained in the function as a number. It is remaining a variable.
var array = [];
for (var i = 0; i<number; i++){
array[i].someFunction = function(i) {console.log(i)}}
However, when I call the value held in that property (i.e.):
console.log(array[2].someFunction)
It returns {console.log(i)} instead of {console.log(2)} which is what I want it to do.
Basically you had some problems in your code, like:
not defining number
using var instead of let
not defining the object
using the same value as parameter of the function
here you have the working solution.
var array = [];
// numbers was not defined.
const number = 10;
// use let instead of var
for (let i = 0; i < number; i++) {
// you are not instantiating your object, here is an example.
array[i] = {
"foo": "bar",
"index": i,
}
// you have to change i to j, because if you use i
// it will be the parameter of the function
array[i].someFunction = function(j) {
console.log('index: ', i);
console.log('parameter: ', j)
}
}
// we see the function
console.log(array[2].someFunction)
// we call the function succesfully
array[2].someFunction(100);
It's still referencing i, which has since changed to (number - 1). Save the value somewhere you know it's not subject to change- perhaps in the object itself:
var array = [{}, {}, {}];
for(var i = 0; i < array.length; i++){
array[i].index = i;
array[i].someFunction = function(){console.log(this.index);}
}
//and see that it's working...
for(var i = 0; i < array.length; i++){
array[i].someFunction();
}
I have a function that simply returns the longest property of a given array.
It's a for loop that assigns the looped property to a variable, with the length of the property is longer than that of the variable.
And at last it returns this new variable. But I get an error in line 10, that it can't read the length of undefined.
It seems to have a problem with someArray[i].length inside the for loop.
function longestString(i) {
// i will be an array.
// return the longest string in the array
var someArray = i;
console.log(someArray);
var longestItem = someArray[0];
console.log(longestItem);
for (i = 0; someArray.length; i++) {
if (longestItem.length < someArray[i].length) {
console.log(longestItem);
console.log(someArray[i]);
longestItem = someArray[i];
}
}
document.write(longestItem);
console.log(longestItem);
return longestItem;
}
longestString(['a', 'ab', 'abc']) // should return 'abc'
Any suggestions?
Your for-loop's condition has error.
It should be like given below.
for (i = 0; i < someArray.length; i++)
Check out this fiddle.
Here is the complete code.
function longestString(i) {
// i will be an array.
// return the longest string in the array
var someArray = i;
document.write(someArray); // just testing
var longestItem = someArray[0];
for (i = 0; i < someArray.length; i++) { //Changes in the condition
if (longestItem.length < someArray[i].length) {
longestItem = someArray[i];
}
}
document.write(longestItem);
return longestItem;
}
longestString(['a', 'ab', 'abc']) // should return 'abc'
First of all don't use the same name ifor the function parameter and then in the for loop counter, you may put yourself in really big troubles.
Second thing, your loop doesn't have a stop condition you missed i<someArray.length, it should be like this:
for (i = 0; i<someArray.length; i++) {
if (longestItem.length < someArray[i].length) {
console.log(longestItem);
console.log(someArray[i]);
longestItem = someArray[i];
}
}
Last thing use console.log() or console.dir() to debug/test instead of document.write() because it's a very very bad practice.
There are two errors on your for loop:
You are using an i function parameter which you are using again in your for loop. Try to use a different variable name inside your for loop or at least define the variable with var (to retain the scope), otherwise you will shadow the variable declared as function parameter.
The second one is that you forget to include the test condition into the loop.
function longestString(len) {
// i will be an array.
// return the longest string in the array
var someArray = len;
var longestItem = someArray[0];
var length = someArray.length;
for (var i = 0 ; i < length; i++) {
if (longestItem.length < someArray[i].length) {
longestItem = someArray[i];
}
}
console.log(longestItem);
return longestItem;
}
longestString(['a', 'ab', 'abc']) // should return 'abc'
Maybe there's more than one longest string. I'd suggest looking at the Array instance iteration methods.
var array = ['a', 'abc', 'ab', 'def'];
var maxlen = Math.max.apply(null, array.map(function(string){
return string.length;
}));
var longest = array.filter(function(string){
return string.length === maxlen;
});
var pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(longest);
document.body.appendChild(pre);
I have a for loop in which I am getting all the values one by one but I need to form those values into one array.
Can any one let me know how to get form all the values into one array.
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
var yourArray = [];
yourArray.push(marray);
console.log(marray);
}
Output getting from the above code is : ["0123"] and ["3456"]
But the expected output is ["0123","3456"]
You are creating a new yourArray for each loop iteration. Instead of doing that, create it just once before starting the loop:
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
Note that I have changed the code to read yourArray.push(mId) because from the question it seems that's what you want -- not yourArray.push(marray).
A more compact way of doing the same is to use the array map function like this:
var yourArray = marray.map(function(row) { return row.id; });
This last version won't work out of the box in IE 8, so if you care about that you need to take appropriate measures.
decalare variable in outside for loop..
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mid);
}
console.log(yourArray);
Initialise yourArray before the loop
Try this
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
The var yourArray is initialized to null each time you enter the loop. Define it outside loop.
I'm trying to implement a duplicate method to the js Array prototype which concats a duplicate of the array to itself like so:
[11,22,3,34,5,26,7,8,9].duplicate(); // [11,22,3,34,5,26,7,8,9,11,22,3,34,5,26,7,8,9]
Here's what I have, but it causes the browser to crash:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var j = this.length;
for(var i = 0; i < this.length; i++) {
this[j] = this[i];
j++;
}
return this;
}
I'm trying to do this using native JS as practice for iterations and algorithms so I'm trying to avoid built-in methods, if possible, so that I can get a clearer understanding of how things are being moved around.
Any ideas on why it is crashing and how I can optimize it?
The code inside the loop changes the length of the array, so it will just keep growing and you will never reach the end of it. Get the initial length of the array in a variable and use in the loop condition. You can use that as offset for the target index also instead of another counter:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var len = this.length;
for (var i = 0; i < len; i++) {
this[len + i] = this[i];
}
return this;
}
The length of the array is increasing with each element added so you can not use this as a terminator. Try this.
var j = this.length;
for(var i = 0; i < j; i++) {
this[i+j] = this[i];
}
Here's simplest code
Array.prototype.duplicate = function () {
var array = this;
return array.concat(array);
};
Using Spread syntax;
In a method, this refers to the owner object.
Array.prototype.duplicate = function () {
return [...this, ...this]
};
let array = [1,2,3,4,5];
Array.prototype.duplicate = function () {
return [...this, ...this]
};
console.log(array.duplicate());
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);