我想將多個具有相同值的元素添加到物件陣列中,例如“.push()”,但有一個計數。我知道我可以做 array.push(a, b, c),但我希望能夠做類似的事情:
person {
firstName: string;
lastName: string;
age: number;
}
people: Person[];
numberPeople: number;
// some calculation to generate numberPeople, example: 23
person.push( {firstName: '', lastName: 'Smith', age: 0}, NumberPeople)
我知道我可以使用回圈結構(for (i=0; i<NumberPeople;i ) person.push),但這很麻煩。有沒有更簡單的方法?我對 JavaScript 和 TypeScript 比較陌生。
我試過 .fill() 但這不允許我指定值。
謝謝,
我知道我可以創建自己的函式( mpush(obj, count) ),但如果有的話,我寧愿使用更優雅和標準的東西。
uj5u.com熱心網友回復:
您可以使用內置fill()方法,首先創建一個Array正確大小的值,然后多次填充它的值。
interface person {
firstName: string;
lastName: string;
age: number;
}
const samplePerson = {firstName: '', lastName: 'Smith', age: 0}
const people = Array(numberPeople).fill(samplePerson)
uj5u.com熱心網友回復:
您可以使用填充,這里是使用 TypeScript 的示例。
type Person = {
firstName: string;
lastName: string;
age: number;
}
let people: Person[]=[];
// you can replace 10 with the calculation
let numberPeople: number = 10;
// this will create an array with all elments having {firstName: '', lastName: 'Smith', age: 0}) as values, with length of numberPeople
people = Array(numberPeople).fill({firstName: '', lastName: 'Smith', age: 0})
uj5u.com熱心網友回復:
我會實時計算添加的內容,因為我正在添加更多的人。
假設它是一個從零開始的陣列,所以 1st 將是 0,即陣列中的索引。
let people = [];
let samples = 23;
for (let i = 0; i < samples; i )
{
let person = { firstName: 'Bob_' i, lastName: 'Smith', age: 0 };
people.push( { index: people.length, person } );
}
// We should now have the 23 people needed.
console.log(people.length); // 23
// Example of the first added.
console.log(people[0]);
/* Results:
{
"index": 0,
"person": {
"firstName": "Bob_0",
"lastName": "Smith",
"age": 0
}
}
*/
uj5u.com熱心網友回復:
.fill()您確實可以使用:
const NumberPeople = 3;
const people = Array(NumberPeople).fill({firstName: '', lastName: 'Smith', age: 0});
console.log(people);
// notice the above method places the same person in all positions
console.log(people[2].age); // will log 0
people[1].age = 4;
console.log(people[2].age); // will log 4
//
//
// if all values being the same object is a problem, you can use .map:
const people2 = [...Array(NumberPeople)].map(_ => ({firstName: '', lastName: 'Smith', age: 0}));
console.log(people2);
console.log(people2[2].age); // will log 0
people2[1].age = 4;
console.log(people2[2].age); // will log 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524740.html
上一篇:Javascript:通過單擊圖庫中的影像將影像存盤在陣列中
下一篇:按索引回傳陣列中的多個特定項
