7

我在javascript中有这样的嵌套数组:

testArray['element1'] = {par1: "value1", par2: "value2" ... }
testArray['element2'] = {par1: "value1", par2: "value2" ... }
testArray['element3'] = {par1: "value1", par2: "value2" ... }
testArray['element4'] = {par1: "value1", par2: "value2" ... }

那么我怎样才能改变元素的位置呢?例如,而不是

("element1", "element2", "element3","element4")
to be
("element4", "element2", "element3","element1")
or
("element1", "element4", "element3","element2")
4

6 回答 6

7

首先,正确构建对象:

array = {
  'element1' : {par1: 'value1', par2: 'value2', par3: 'value3'....},
  'element2' : {par1: 'value1', par2: 'value2', par3: 'value3'....},
  'element3' : {par1: 'value1', par2: 'value2', par3: 'value3'....},
  'element4' : {par1: 'value1', par2: 'value2', par3: 'value3'....}
}

然后交换:

var tmp = array['element2'];
array['element2'] = array['element1'];
array['element1'] = tmp;
于 2012-09-10T19:38:14.107 回答
7

您在问题中发布的内容不是数组,甚至不是有效的 javascript 语法。由于您询问顺序,我假设您没有使用对象,因为 javascript 中的对象没有保证顺序。

话虽这么说,我假设你有一个这样声明的数组:

var testArray = [{ ... }, { ... }, { ... }];

要交换两个元素,您只需要一个通用交换函数:

var swap = function(theArray, indexA, indexB) {
    var temp = theArray[indexA];
    theArray[indexA] = theArray[indexB];
    theArray[indexB] = temp;
};

swap(testArray, 0, 1);

http://jsfiddle.net/jbabey/gRVn5/

于 2012-09-10T19:58:23.317 回答
2

您可以将其添加为数组原型,如下所示:

Array.prototype.swap = function (index1, index2) {
    if (index1 <= this.length && index2 <= this.length) {
        var temp = this[index2];
        this[index2] = this[index1];
        this[index1] = temp;
    }
};
于 2014-08-15T15:56:17.883 回答
1
arr = [0,1,2,3];
a = arr[3];
arr[3] = arr[0];
arr[0] = a;
于 2013-11-09T02:09:50.043 回答
0

我只想写一个交换函数。

var letters = "abcdefghijklmnopqrstuvwxyz".split("");

function swap(theArray, index1, index2) {
  var temp = theArray[index2];
  theArray[index2] = theArray[index1];
  theArray[index1] = temp;
}

swap(letters, 2, 25); // swap "c" and "z"
于 2012-09-10T20:05:35.290 回答
0

您现在可以执行以下操作:

let list = [1,2,3,4];
[list[1],list[3]] = [list[3],list[1]];

//Result: [1,4,3,2]
于 2021-02-09T13:14:23.457 回答