This question already has answers here:
Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop
(25 answers)
Closed 5 years ago.
I need one clarification java script. I used two variables in my program.
I stored particular array in first variable and again create one variable.
I have stored second variable value in first variable.Then I pushed one vale in second variable... If i print first variable means second variable vale displayed..
My expectation is first variable value don't want to change..
// first variable
var test = ["a","b","c"];
// second variable
var arr = test;
arr.unshift("d");
// second variable print
console.log(arr); // ["a","b","c","d"]
// First variable print
console.log(test); // ["a","b","c","d"]
// I want to maintain first original value
// Expectation result
console.log(test); // ["a","b","c"]
I need maintain original value in first variable..What I do?
You can use the spread operator (check browser capability)
var arr = [...test];
// first variable
var test = ["a","b","c"];
// second variable
var arr = [...test];
arr.push("d");
// second variable print
console.log(arr); // ["a","b","c","d"]
// First variable print
console.log(test); // ["a","b","c","d"]
// I want to maintain first original value
// Expectation result
console.log(test); // ["a","b","c"]
Related
This question already has answers here:
Copy array by value
(39 answers)
Closed 3 years ago.
So I need the original(argument) array to stay the same, AND have another array (array2) with it's values to make some changes on it but mantain the original(argument) array intact.
Example:
let wtf = function(array){
let array2 = array
array2[0] = array2[0].replace(array2[0][0],"1")
console.log( array + " " + array2)
}
wtf(["a","b"])
Result in console:
1,b 1,b
BUT I need a,b 1,b
(that comes from: array = a,b and array2 = 1,b )
Thanks!
I think this is a reference value vs a clone value problem.
With your let array2 = array line, I think you're creating a reference to the same in-memory object, so you're actually modifying a single array twice, even though it looks like you've created another one.
To create a 'true' clone you can try something like:
let array2 = JSON.parse(JSON.stringify(array));
This question already has answers here:
What's the difference between empty items in a JavaScript array and undefined? [duplicate]
(2 answers)
Closed 4 years ago.
If I create the following constant in the browser console:
const myArray = Array(2);
This outputs the following:
(2) [empty × 2]
And when I use the spread operator in the following manner:
const myUndefinedArray = [...myArray]
Then the console returns:
(2) [undefined, undefined]
In both cases it says the length is two. What are the use cases for each of these options? Is there any specific implication to "empty"?
main difference would be forEach and map properties
Array(2).map(()=>"value") will not do anything
[undefined,undefined].map(()=>"value") will map
The empty values aren't iterable:
var arr = new Array(5)
arr.forEach(()=> console.log('hello'))
var arr2 = [...arr]
arr2.forEach(()=> console.log('world'))
Empty in an array means the index has never been assigned a value. This has to do with how Javascript deals with arrays. You can try this:
var v = new Array();
v[0]=undefined;
v.length = 2
console.log(v);
See, array index 0 has a "property" with name "0", without a value assigned to it (i.e. undefined). The array, however, does not have a property with name "1" at this point. Chrome logs this as "empty" value.
const myArray = Array(2);
console.log(myArray)
You're creating here an empty with length 2, that's why you're getting the output of an array with 2x empty values as you didn't put any values inside the created array.
const myArray = Array(2);
const myUndefinedArray = [...myArray]
console.log(myUndefinedArray)
You get here undefined because you're trying to create an myUndefinedArray array using nonexistent values.
This question already has answers here:
Change the value of an array changes original array JavaScript
(3 answers)
Closed 6 years ago.
Maybe the question already exists, but I don't find anything because I don't know how to call this problem.
I have an object function and want to assign the object variable into a variable:
this.myFunction = function() {
var selection; // internal variable
selection = this.selection; // both are [0,0]
console.log(this.selection); // result: [0,0]
selection[0] = 500; // set internal variable[0] 500
console.log(selection); // result: [500,0]
console.log(this.selection); // result: [500,0] <-- expected: [0,0]
}
How I can change the local variable without changing the other?
When you call selection = this.selection, you are copying the reference of this.selection value. So when you change the local variable selection, you are changing this.selection too.
You have to use the method slice() to create a new array from the value. Like this:
selection = this.selection.slice();
This question already has an answer here:
Changing variable in another function in JavaScript
(1 answer)
Closed 7 years ago.
I am trying to automate the changing of a variable through a function. However although it returns the right value, it doesn't change the actual value of the variable passed to it.
function change(one, two){
one = two;
return one;
}
var test = 1;
change(test, 5);
// returns 5;
console.log(test);
// still 1
Why does this happen and how can I solve this?
You can't pass variables. When you call change(test, 5); you are passing the value of test not the variable test.
That value is copied to the variable one.
You then assign a new value to one, but that doesn't touch test.
If you want to do anything like this, you need to pass an object and then modify the value of a property of the object.
function change(one, two){
one.test = two;
return one.test;
}
var myObject = {
test: 1
};
change(myObject, 5);
console.log(myObject.test);
You can't do this in JavaScript. Variables cannot be passed by reference, they are always passed by value.
This question already has answers here:
Copy array by value
(39 answers)
When I assign a variable to another variable does it not link them together?
(1 answer)
Closed 9 years ago.
I have really weird situation:
when I do that code:
var origin_array = [1,2,3];
var m = origin_array;
m.pop();
alert(origin_array);
origin_array value will be 1,2
eventhough I didn't changed it
but if I make that code:
var x = 5;
var y = x;
y--;
alert(x);
x still be 5, it won't be connected to "x" as you can see from the 1st example.
So my question is how do I make the "m" array unique, which not change the origin array?
You need to explicitly make a (shallow) copy or clone of origin_array:
var m = origin_array.slice(0);
This is not needed for primitive values, such as strings and numbers.
It's important to understand that although the above will prevent the issue you were experiencing, the same may happen again deeper down if you're dealing with more complex structures, and in some cases a "deep clone" is necessary.
Arrays are assigned by reference. That means that when you do this:
var origin_array = [1,2,3];
var m = origin_array;
m just points to the exact same array as origin_array. There is only one array and both origin_array and m point to it. If you modify it via either variable, they will both see the modification because you're modifying the one array that they both point to.
In javascript, both objects and arrays are assigned by reference like this. Assigning them does NOT make a copy. If you want an assignment to generate a copy, you have to explicitly make a copy. For an array, that is easy as you can just do:
var origin_array = [1,2,3];
var m = origin_array.slice(0); // makes a shallow copy
m.pop();
console.log(origin_array); // [1,2,3] because origin_array was not changed