将嵌套数组转换为对象

时间:2011-07-19 11:17:17

标签: javascript arrays object arguments

我正在寻找一种解决方案,将数组项目推送/转换回对象,而不使用密钥?

function pleaseBuy(){
    var args = arguments;
    for(var i = 0; i < arguments[0].length; ++i) {
        args += args[i];
    };
};

function getList(){
   return ["pepsi","cola","7up"];
}

var list = ({ favorite: "drpepper"}, getList())
pleaseBuy(list)

预期结果:

args = ({ favorite: "drpepper"}, "pepsi", "cola", "7up")

5 个答案:

答案 0 :(得分:2)

不需要pleaseBuy功能,我会说:

function getList(){
   return ["pepsi","cola","7up"];
}

var list = getList().concat( { favorite: "drpepper" } );
//                                     ^ NB should be :
// or favorite first
var list = [{ favorite: "drpepper" }].concat(getList());
/* 
   list now contains:
   ['pepsi, 'cola','7up',{ favorite: "drpepper" }]
*/

对象总是包含键值对。如果要将数组转换为对象,则必须分配键和值。例如:

var arr = [1,2,3,4,'some'], arr2Obj = {};
for (var i=0;i<arr.length;i=i+1){
   arr2Obj[arr[i]] = i;
}

/* 
   arr2Obj now contains:
   { 
     1: 0,
     2: 1,
     3: 2,
     4: 3,
     some: 4
   }
*/

其他例子:

var arr = [1,2,3,4,'some'], arr2Numbers = {};
for (var i=0;i<arr.length;i=i+1){
       arr2Numbers[arr[i]] = !isNaN(Number(arr[i]));
}
/* 
   arr2Numbers now contains:
   { 
     1: true,
     2: true,
     3: true,
     4: true,
     some: false
   }
*/

答案 1 :(得分:1)

您的意思是javascript push功能吗?

答案 2 :(得分:1)

使用.unshift() docs作为数组的前缀。

var list = getList();
list.unshift( { favorite="drpepper"});

// [{ favorite="drpepper"}, "pepsi", "cola", "7up"]

http://jsfiddle.net/Ds9y5/

演示

答案 3 :(得分:0)

试试这个:

var array = ["pepsi","cola","7up"];
array.push({ favorite: "drpepper"});

或者

var array2 = ["pepsi","cola","7up"];
var array = [{favorite: "drpepper"}];
for(var ctr = 0 ; ctr < array2.length ; ctr++){
  array.push(array2[ctr]);
}

答案 4 :(得分:0)

var s = getList();
s.unshift({ favorite : "drpepper"}); // at the first place in array
s.push({ favorite : "drpepper"}); // at the last place in array
alert(s);

JavaScript push() Method
JavaScript unshift() Method