简体   繁体   English

根据长度创建对象数组; 每个 object 都有一个以索引 + 1 作为其值的属性

[英]Create array of objects based on length; each object has a property with the index + 1 as its value

I want to improve my ugly code to something more clean and simple.我想将我丑陋的代码改进为更干净和简单的东西。 How can I shorten this code?如何缩短此代码?

if (this.foo < 2) {
  return (this.result = [ { year: 1 } ]);
}
if (this.foo < 3) {
  return (this.result = [ { year: 1 }, { year: 2 } ]);
}
if (this.foo < 4) {
  return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 } ]);
}
if (this.foo < 5) {
  return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 }, { year: 4 } ]);
}
if (this.foo < 6) {
  return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 }, { year: 4 }, { year: 5 } ]);
}

Create an array with Array , and use Array.prototype.map .使用Array创建一个数组,并使用Array.prototype.map

 function func(foo) { return Array(foo).fill().map((f, i) => ({ year: i + 1 })); } console.log(func(1)); console.log(func(3));

What you've shown is equivalent to this (except this goes beyond five elements, but also beyond one in the other direction):您所展示的内容与此等效(除了这超出了五个元素,而且还超出了另一个方向的一个):

return this.result = Array.from({
  length: Math.floor(this.foo)
}, (_value, index) => ({
  year: index + 1
}));

This assumes that this statement is inside a function (otherwise, return wouldn't work).这假定此语句位于 function 内(否则, return将不起作用)。

A more reasonable length may be Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo))) which clamps 1 the length to at least 0 and at most 2 32 − 1, the maximum Array length .更合理的长度可能是 Math.max(0, Math.min(2 ** 32 - 1 Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo))) ,它将长度限制为至少 0 和最多 2 32 - 1, 最大数组长度

If you want to always have at least one element in your array, then use Math.max(1,) instead.如果您希望数组中始终至少有一个元素,请改用Math.max(1, ... )

Returning an assignment (ie return this.result =; ) is frowned upon .返回一个作业(即return this.result = ... ; )是不受欢迎的 The best practice is to separate these statements 2 :最佳做法是将这些语句2分开:

this.result = Array.from({
  length: Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo)))
}, (_value, index) => ({
  year: index + 1
}));

return this.result;

Array.from is used with both arguments: the first one is the “array-like” object { length: Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo))) } which gets converted to a proper Array object. Array.from与 arguments 一起使用:第一个是“类似数组”的 object { length: Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo))) }它被转换为正确的Array object。 In this case, an array with a length of Math.floor(this.foo) is initialized (clamped to the range of possible Array lengths).在这种情况下,将初始化一个长度为Math.floor(this.foo)的数组(限制在可能的数组长度范围内)。 The second argument maps each value at a certain index to an object with the year property with the value index + 1 .第二个参数将某个index处的每个值映射到 object ,其中year属性的值index + 1 _value isn't used (it's undefined anyway). _value未使用(无论如何它是undefined的)。

The advantage to use Array.from( array-like , mapping-function ) over eg .fill().map() is that only a single array is created in memory.使用Array.from( array-like , mapping-function )优于.fill().map()的优点是在 memory 中只创建了一个数组。 Array().fill().map() creates two new arrays: the first one at Array().fill() , the second one at .map() . Array( ... ).fill().map( ... )创建两个新的 arrays:第一个在Array( ... ).fill() ,第二个在.map( ... ) Therefore, the Array.from approach is more memory-efficient.因此, Array.from方法更节省内存。


1 : Maybe soon we'll finally get a Math.clamp method… 1 :也许很快我们就会得到一个Math.clamp方法……

2 : Technically, this would be equivalent. 2 :从技术上讲,这将是等效的。 If this.result is a getter / setter, there may be an observable difference.如果this.result是一个 getter / setter,可能会有明显的差异。

const result = Array.from({
    length: Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo)))
  }, (_value, index) => ({
    year: index + 1
  }));

this.result = result;

return result;

try this oneliner试试这个oneliner

let x=3;
let result = [ ...Array(x).keys() ].map(item=> {return{"year":item}});
console.log(result);
let arr = [];

for(let i = 1; i<this.foo;i++){ 
    arr.push({ 'year':i}) 
};

console.log(arr);

暂无
暂无

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

相关问题 通过基于javascript中每个对象的属性值对对象数组进行分组来创建新的对象数组 - Create new array of objects by grouping array of objects based on property value of each object in javascript 对象数组:为每个具有值的指定键创建新对象 - Array of Objects: Create new object for each specified key that has a value 循环遍历以数组为值的 Object 并为其值作为信息的每个键创建 div - Loop through Object which has Array as value and create div for each key with its value as information 根据属性值创建多个对象数组,然后遍历每个数组 - Create multiple arrays of objects based on property value then iterate through each array 如何 map 对象数组并返回每个对象值的长度? - How to map Array of Objects and return the length of each Object's value? 根据属性值创建新的对象数组 - Create new Array of object based on the Property Value 按每个对象具有的属性对对象数组进行排序时,结果异常 - Unusual results when sorting an array of objects by a property each object has JavaScript获得对象数组的值或属性(如果对象具有该属性) - JavaScript get value or property of an Array of objects if object has that property 过滤基于 object 的对象数组,其中数组作为其属性值在反应 - filter an array of objects based on an object with an array as it's property value in react 具有对象数组的Javascript; 对象中的属性具有值,返回未定义 - Javascript with Array of Objects; Property in Object has Value, returns Undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM