例如,在
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 + ' ') });我知道为数组元素实现swap函数的唯一方法是传入数组。但是,这似乎效率低下。 必须有一种方法可以为任何类型的变量实现直接swap功能。 我想我的问题可以归结为:
在JavaScript中实现交换功能的最有效方法是什么?
在将变量传递给经典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; } 程序?
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. There must a way of implementing a straight-up swap function for variables of any type. I guess my question really boils down to:
What is the most efficient way of implementing a swap function in 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; } procedure?
最满意答案
如果使用ECMAScript6,则可以使用解构来交换。
var a = 0; var b = 1; [a, b] = [b, a];这非常方便,也是我喜欢Javascript的原因之一。
但在使用之前请检查兼容性。 否则你必须使用temp var。
您可以使用该方法反转数组。
var arr = [1,2,3,4,5,6,7]; arr.reverse(); // [7,6,5,4,3,2,1]传递数组也不是低效的。 您所做的只是传递对数组的引用,并且比从数组传递两个元素更有效。
所有变量都通过引用在内部进行标识,当您将引用传递给函数时,数组或对象的大小对代码速度没有影响。
If you use ECMAScript6 you can use destructuring to swap.
var a = 0; var b = 1; [a, b] = [b, a];Which is very handy and one of the reasons I love 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.
更多推荐
发布评论