I want to write a function named concatArray(array1, array2)
that takes two arrays as parameters. This function should return a new array that is a combination of those two.
I tried this, but in the console it shows: 'array1 is not defined'.
function concatArray(array1, array2) {
var array1 = [1, 3, 7];
var array2 = [12, 21, 42];
}
console.log(array1.concat(array2));
The expected output should be this: 1,3,7,12,21,42
Let me break my answer into a few parts:
var
inside of a function, you have declared a variable that can only be accessed from within that function block. If you were to call console.log from within the function block, it would be defined. Eg:
function concatArray(array1, array2) {
var array1 = [1, 3, 7];
var array2 = [12, 21, 42];
console.log(array1.concat(array2));
}
Like this:
function concatArray(array1, array2) {
console.log(array1.concat(array2));
}
Try something like this:
// define our function
function concatArray(array1, array2) {
// return two concatted arrays
return array1.concat(array2);
}
// define our arrays
var myArray1 = [1, 3, 7];
var myArray2 = [12, 21, 42];
//invoke the function with our arrays as params and assign it to a variable
var result = concatArray(myArray1, myArray2);
//console log new results
console.log(result);
What you need to be doing is done in your console.log statement. But here is the solution
var array1 = [1, 3, 7];
var array2 = [12, 21, 42];
function concatArray(array1, array2) {
return array1.concat(array2);
}
console.log(concatArray(array1, array2));
Your question is unclear, maybe you're looking for something like that?
function concatArray(arr_1, arr_2) { return [].concat(arr_1, arr_2) // eq return arr_1.concat(arr_2) } var array1 = [1, 3, 7]; var array2 = [12, 21, 42]; var array3 = concatArray(array1, array2); console.log('array1',JSON.stringify(array1)); console.log('array2',JSON.stringify(array2)); console.log('array3',JSON.stringify(array3));
You can use the spread operator from ES6.
function concatArray(array1, array2) {
return [...array1, ...array2];
}
var array1 = [1, 3, 7];
var array2 = [12, 21, 42];
console.log(concatArray(array1, array2));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.