繁体   English   中英

将嵌套数组转换为 object

[英]Convert nested array to object

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

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")

不需要请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" }]
*/

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

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
   }
*/

你的意思是javascriptfunction?

使用.unshift()文档添加到数组中。

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

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

演示在http://jsfiddle.net/Ds9y5/

尝试这个:

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]);
}
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() 方法
JavaScript unshift() 方法

暂无
暂无

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

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