I want to make a function that completely override the original array.
function putDatainthis(arr) {
//....some ways to get data
arr = [data,data,data...]; //this just reassigns arr = to new array original that was passed as reference hasn't been modified.
}
//so right now only way i can think of is this:
function putDatainthis(arr) {
var data = [3,4,6,2,6,1];
arr.length=0;
data.forEach(function(e){
arr.push(e);
});
}
but i want to know can it be improved or is there more native way.
cнŝdk
32.2k7 gold badges62 silver badges81 bronze badges
asked Sep 7, 2015 at 16:11
Muhammad Umer
18.3k26 gold badges111 silver badges179 bronze badges
-
basically i want replace functionMuhammad Umer– Muhammad Umer2015年09月07日 16:15:21 +00:00Commented Sep 7, 2015 at 16:15
3 Answers 3
The Array.prototype.splice() function is what you are looking for, this is your way to go:
function putDataInThis(arr) {
var data = [3, 4, 6, 2, 6, 1];
arr.length = 0;
arr.splice(0, arr.length, data);
return arr;
}
alert(putDataInThis(["h", "g"]).join(","));
Explantation:
In the following arr.splice(0, arr.length, data) statement, we used splice() function with the following parameters:
0the beginning index for the replacement.arr.lengthas the number of elements to replace.- And
datais the list of new values to put in our array.
Read Array.splice( ): insert, remove, or replace array elements for further information.
answered Sep 7, 2015 at 16:40
cнŝdk
32.2k7 gold badges62 silver badges81 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I think you could use jquery merge.
function putDatainthis(arr) {
var data = [3,4,6,2,6,1];
$.merge(arr, data);
}
answered Sep 7, 2015 at 16:31
Syam S
8,5071 gold badge29 silver badges37 bronze badges
1 Comment
Muhammad Umer
i will be using it in nodejs
Try this way.
function putDatainthis(arr) {
var data = [3,4,6,2,6,1];
var concat_array = data.concat(arr);
}
answered Sep 7, 2015 at 16:37
Jakir Hossain
2,51720 silver badges24 bronze badges
1 Comment
Muhammad Umer
arr has not changed in this example
lang-js