简体   繁体   English

在 JavaScript 中用 object 填充数组而不编写循环的最简单方法?

[英]Easiest way to fill array with an object in JavaScript without coding a loop?

Say I have the following object:假设我有以下 object:

var obj = { foo: 'bar' };

I want to add this object to an array X amount of times so the result is:我想将这个 object 添加到数组 X 次,所以结果是:

[{ foo: 'bar' }, { foo: 'bar'}, ... , { foo: 'bar'}]

Is there a way to accomplish this without explicitly coding a loop?有没有一种方法可以在不显式编写循环的情况下完成此操作?

There is a way: manually. 有一种方法:手动。 Any programmatic solution will indeed use a loop here, which, if you wish to maintain your sanity -- use it. 任何程序化的解决方案都会在这里使用循环,如果你想保持理智 - 使用它。

你可以使用地图

var filled = Array.apply(null, Array(501)).map(function() { return {"foo":"bar"} });

You can do this using .fill 你可以使用.fill来做到这.fill

const someArray = ['test']; // Any other data you may have
const resultingArray = new Array(100).fill({ foo: 'bar' }).concat(someArray);

Set 100 to whatever number you need, concat any extra data after (or before if needed) 设置100到任何你需要的数量, concat后的任何额外的数据(或者如果需要的话之前)

As @isvforall pointed out this isn't a deep copy and is done via reference so changing any of the elements in the array would affect all of the others which reference the same object. 正如@isvforall指出的那样,这不是一个深层副本,而是通过引用完成的,因此更改数组中的任何元素都会影响引用同一对象的所有其他元素。 Best used if your values are primitives. 如果您的值是基元,则最佳使用。

I think epascarello's answer is already a winner, and I +1'd it, but here's another approach just for kicks, using your Array.join() trick along with JSON.stringify() and JSON.parse() . 我认为epascarello的答案已经是胜利者了,我给它+1了,但这是另一种方法,只是为了踢,使用你的Array.join()技巧以及JSON.stringify()JSON.parse()

Verbose: 详细:

var obj = { foo: 'bar' };
var objJSON = JSON.stringify(obj);
var list = new Array(501).join(objJSON + ',')
var trimmedList = list.substr(0, list.length - 1); // getting rid of that last comma
var arrayJSON = '[' + trimmedList + ']';
var array = JSON.parse(arrayJSON);
console.log(array);

Compact: 紧凑:

var list = new Array(501).join(JSON.stringify({ foo: 'bar' }) + ',')
var array = JSON.parse('[' + list.substr(0, list.length - 1) + ']');
console.log(array);

If you really don't want a loop you can use recursion. 如果你真的不想要一个循环,你可以使用递归。

function objFillArray(obj, count) {
    let ret = [];
    return notALoop();
    function notALoop() {
        ret.push(obj);
        if( --count ) return notALoop();
        return ret;
    }
}

this will keep calling notALoop count number of times adding the object to the returned array. 这将继续调用notALoop count次数将对象添加到返回的数组。

Using recursion and concat function 使用递归和concat函数

var obj = { foo: 'bar' };

var result = (function fill(a, len) {
    return a.length == len ? a : fill(a.concat(obj), len);
})([], 10);

 var obj = { foo: 'bar' }; var result = (function fill(a, len) { return a.length == len ? a : fill(a.concat(obj), len); })([], 10); document.write(JSON.stringify(result)); 

The callback function in Array.from can be used to ensure each element of the array is a different reference. Array.from 中的回调Array.from可用于确保数组的每个元素都是不同的引用。

 const arr = Array.from({length: 5}, _=>({foo: 'bar'})); console.log(arr);

If all elements are meant to be the same reference, directly use Array#fill .如果所有元素都意味着相同的引用,请直接使用Array#fill

 const arr = Array(5).fill({foo: 'bar'}); console.log(arr);

Use .push() function to assign value to an array. 使用.push()函数为数组赋值。

    yourarray.push(yourobject);
               |
               |
               |
               V
    fiveHundredChars.push(obj);

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

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