简体   繁体   English

在JavaScript中,是否有任何方法可以将数组的元素传递到函数中而不传递整个数组?

[英]In JavaScript, is there any way of passing elements of an array into a function without passing in the entire array?

For example, in 例如,在

function swap ( arr, i1, i2 ) 
{
    // swaps elements at index i1 and i2
    // in the array arr
    var temp = arr[i1];
    arr[i1] = arr[i2];
    arr[i2] = temp;
}

function reverse_array ( arr ) 
{
    // reverse the order of the elements in array arr
    var i1 = 0, i2 = arr.length;
    while ( i1 != i2 && i1 != --i2 ) swap(arr,i1++,i2);
}

var myArray = [1, 2, 3, 4];
reverse_array(myArray);
myArray.forEach(function(elem) { $('#mydiv').append(elem + ' ') });

the only way I know of implementing a swap function for elements of an array is to pass in the array in. However, that seems inefficient. 我知道为数组元素实现swap功能的唯一方法是将数组传入。但是,这似乎效率很低。 There must a way of implementing a straight-up swap function for variables of any type. 必须有一种方法可以为任何类型的变量实现直接swap函数。 I guess my question really boils down to: 我想我的问题真的可以归结为:

What is the most efficient way of implementing a swap function in JavaScript??? 在JavaScript中实现交换功能的最有效方法是什么?

Is there a way of "boxing" (to use a C# term) to variables before passing them into a classic function swap ( a, b ) { temp = a; a = b; b = temp; } 在将变量传递到经典function swap ( a, b ) { temp = a; a = b; b = temp; }之前,是否可以对变量进行“装箱”(使用C#术语) function swap ( a, b ) { temp = a; a = b; b = temp; } function swap ( a, b ) { temp = a; a = b; b = temp; } function swap ( a, b ) { temp = a; a = b; b = temp; } procedure? function swap ( a, b ) { temp = a; a = b; b = temp; }程序?

If you use ECMAScript6 you can use destructuring to swap. 如果使用ECMAScript6,则可以使用分解交换。

var a = 0;
var b = 1;
[a, b] = [b, a];

Which is very handy and one of the reasons I love Javascript. 这非常方便,也是我喜欢Javascript的原因之一。

But check for compatability before you use it. 但是在使用前请检查兼容性。 Otherwise you have to use a temp var. 否则,您必须使用临时变量。

You can reverse an array with the method. 您可以使用该方法反转数组。

var arr = [1,2,3,4,5,6,7];
arr.reverse(); // [7,6,5,4,3,2,1]

Also passing an array is not inefficient. 同样,传递数组并不是没有效率的。 All you do is pass a reference to the array, and is more efficient than passing two elements from the array. 您要做的就是将引用传递给数组,并且比传递数组中的两个元素更有效。

All variables are identified internally via a reference, the size of the array or object has no effect on code speed when you pass the reference to functions. 所有变量都通过引用在内部进行标识,将引用传递给函数时,数组或对象的大小不会影响代码速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM