简体   繁体   English

如何在Javascript中创建Arrays的object?

[英]How to create object of Arrays in Javascript?

I want to create a object of Arrays, how to create it?我想创建一个Arrays的object,如何创建呢?

const obj = {};
let i = 1;

function* id() {
  while (true) {
    i++;
    yield i;
  }
}

function data(first, middle, last) {
  const arr = [first, middle, last];
  let key = id();
  obj[key.next().value] = arr;
  console.log(obj);
}

data("rohit", "kumar", "sharma");
data("rohit", "kumar", "sharma");

I got the correct out but i want to ask is any other method?我得到了正确的,但我想问一下还有其他方法吗?

Your code is fine but it forces you to create only array of three elements.您的代码很好,但它会强制您只创建三个元素的数组。 Here is a code more flexible:这是一个更灵活的代码:

const obj = {};

function data(arr) {
  let key = id();
  obj[key.next().value] = arr;
  console.log(obj);
}

data(["rohit", "kumar", "sharma"]);
data(["rohit", "kumar", "sharma"]);

I don't know your need but creating an object with incremental value as properties make me think that an array of array would be easier to use instead.我不知道您的需求,但是创建一个具有增量值作为属性的 object 让我认为数组的数组更容易使用。

EDIT编辑

To simplify everything if you really want to keep an object:如果你真的想保留一个 object,为了简化一切:

const obj = {};
let i = 0;
function data(arr) {
  obj[i++] = arr;
  console.log(obj);
}

data(["rohit", "kumar", "sharma"]);
data(["rohit", "kumar", "sharma"]);

If you are ok to use an array, you don't need a function:如果您可以使用数组,则不需要 function:

const arr = [];

arr.push(["rohit", "kumar", "sharma"])
arr.push(["rohit", "kumar", "sharma"])

console.log(arr[0])
console.log(arr[1])

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

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