路过的Javascript数组作为参数的功能 [英] Javascript passing array as parameter to function

查看:186
本文介绍了路过的Javascript数组作为参数的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数,接受数组作为参数,这些功能做一个简单的工作,使得阵列的所有元素为零。

I have two function that accept an array as parameter, these function do a simple work, making all element of the array to zero.

使用的forEach()方法并传递一个回调呢?首先功能:

First function using forEach() method and passing a callback to it:

function pass_arr(x)
{
  x.forEach(function(y){
    y = 0;
  });
}

和我叫它是这样的:

var a = ["a", "b", 1, 3, "stringg"];
pass_arr(a);

然后打印数组的内容:

Then printing the content of array a:

for(var i = 0; i < a.length; i++)
{
  console.log(a[i]);
}

我执行这个节点使用

I execute this using node:

#nodejs func.js

和得到的结果。

a
b  
1
3
stringg

使用正常的函数调用二级功能:

Second function using normal function call :

function pass_arr(x)
{  
  for(var i = 0; i < a.length; i++)
  {
    x[i] = 0;
  }
}

var a = ["a", "b", 1, 3, "stringg"];
pass_arr(a);
for(var i = 0; i < a.length; i++)
{
   console.log(a[i]);
}

#node func.js

和得到的结果:

0
0
0
0
0

据我知道,当我们传递一个数组给一个函数,那么我们做参照通,因此,我们可以修改的内容函数内部的数组。

我的问题是,为什么第一个函数没有正确归零数组的内容?请给一些明确的解释?

My question is why the first function doesn't properly zeroing the content of the array? Please give some clear explanation?

推荐答案

X 指向同一个阵列,因此使用 X [i] = 将写入 X 的第i个元素。当您使用 .forEach 参数回调是的原始的中如果您的阵列。如果你写一个原始的,它不会改变原来的数组。也就是说,你不能使用 .forEach 通过写原语来改变原有的数组。但是,您仍然可以改变以同样的方式原始数组:

x points to the same array, so using x[i] = will write to the ith element of x. When you use .forEach, y the argument to the callback is a primitive in the case of your array. If you write to a primitive, it will not alter the original array. That is to say you cannot use .forEach to alter the original array by writing to primitives. However, you can still alter the original array in the same way:

x.forEach((y, idx) => x[idx] = 0);

这是有点风马牛不相及,但一个办法做到这一点是使用 .MAP

This is somewhat unrelated, but a way to do this would be to use .map.

x = ["a", "b", 1, 3, "stringg"].map(function (y) { return 0; });


我要指出的是,多维数组,由回调所采取的参数不是数组元素的副本,但将指向原来的元素。


I want to point out that in multi dimensional arrays, the argument taken by the callback is not a copy of the array element but will point to the original element.

let x = [[0]];
x.forEach(y => y[0] = 1);
// x is now [[1]]


另外请注意,JavaScript的(以及Java和许多其他语言)都通通过引用汉语语言。所有的参数都是按值传递 - 这只是对象和数组是由自己通过引用存储在变量中。这就是让你在功能变异它们的属性。


Also note that JavaScript (as well as Java and many other languages) are not pass-by-reference langauges. All arguments are passed by value -- it's just that objects and arrays are stored in variables by references that are themselves passed. This is what allows you to mutate their properties in functions.

这篇关于路过的Javascript数组作为参数的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆