[英]Javascript array concatenation
I have three variables a, b and c. 我有三个变量a,b和c。 I have to insert these into an array called
arr
. 我必须将它们插入称为
arr
的数组中。 On calling function click, these variables should get pushed into arr
array. 在调用函数单击时,这些变量应被推入
arr
数组。 eg. 例如。 if i call click with arg 1,2 & 3 then array should be [1,2,3], now when I will pass the args 6,7 then the array should be [1,2,3,6,7].
如果我用arg 1,2&3调用click,则数组应为[1,2,3],现在当我将传递args 6,7时,则数组应为[1,2,3,6,7]。 In the code below, I tried to use
concat
method to get the desired result but i was unsuccessful.Is there any way around this? 在下面的代码中,我尝试使用
concat
方法来获得所需的结果,但我没有成功。是否有解决办法?
function click(a,b,c){ var A=a; var B=b; var C=c; var arr=[] var newArr=[A,B,C] arr.concat(newArr); console.log(arr); } click(10,11,12); click(12,13,14);
Declare a global array outside of the function and then after push values into it. 在函数外声明一个全局数组,然后将值压入其中。
var arr = []; function click(a,b,c){ arr.push(a, b, c) } click(10,11,12); click(12,13,14); console.log(arr);
The problem with your code is that, you are concatenating to the array but not considering the return value. 代码的问题在于,您正在连接到数组,但没有考虑返回值。
arr = arr.concat(newArr);
Then declare the array global to hold the values for every click. 然后将数组声明为全局数组,以保存每次单击的值。
function click(arr, a, b, c){ arr.push(a, b, c); console.log(arr); } var arr = []; click(arr, 10, 11, 12); click(arr, 12, 13, 14);
If you don't want your arr
outside your function, another approach is storing your arr
inside click
scope then call it anywhere (it doesn't pollute your global scope ): 如果您不希望将
arr
放在函数之外,另一种方法是将arr
存储在click
作用域中,然后在任意位置调用它(不会污染您的全局作用域 ):
let click = (function (arr) { return function (a,b,c) { var A=a; var B=b; var C=c; var newArr=[A,B,C] arr = arr.concat(newArr); console.log(arr); } })([]) click(10,11,12); click(12,13,14);
First of all. 首先。 You should either define
arr
outside your function or pass arr
into function as a parameter. 您应该在函数外定义
arr
或将arr
作为参数传递给函数。 Second one. 第二个。 Function
concat
returns concatenated arrays and left original arrays unchanged. 函数
concat
返回串联的数组,并使原始数组保持不变。 So you need something like arr=arr.concat(newArr)
所以你需要像
arr=arr.concat(newArr)
Your Problem here is that the concat function returns a new array instance with the elements: Check Here 在这里你的问题是,concat函数返回一个新的数组实例与要素: 检查这里
function click(a,b,c){
var A=a;
var B=b;
var C=c;
var arr=[]
var newArr=[A,B,C]
arr = arr.concat(newArr);
// concat does not change the ref itself
console.log(arr);
}
click(10,11,12);
click(12,13,14);
Destructuring assignment
can be used to functionally concatenate
variables
with arrays
. Destructuring assignment
可用于在功能concatenate
variables
与arrays
concatenate
。
See below for a practical example. 请参见下面的实际示例。
// Input. const input = [1, 2, 3] // Click. const click = (array, ...arguments) => [...array, ...arguments] // Output. const output = click(input, 4, 5, 6) // Proof. console.log(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.