gpt4 book ai didi

javascript - 如何根据动态变量将元素插入数组

转载 作者:行者123 更新时间:2023-11-30 07:19:53 25 4
gpt4 key购买 nike

我有一个对象,我想用对象属性填充一个数组,并根据每个属性的值重复多次。一个例子:

obj = {
watches: 3
rings: 1
}
// => ['watches', 'watches', 'watches', 'rings']

以下是我目前所拥有的。我很难弄清楚如何根据关联值重复每个属性?

function arrayBuilder(obj) {
let objToArr = [];

for (let [property, value] of Object.entries(obj)) {
objToArr.push(property);
}
return objToArr;
}

console.log(arrayBuilder({watches: 3, rings: 1}));
// => [ 'watches', 'rings' ]

最佳答案

您只是缺少一个内部循环:

function arrayBuilder(obj) {
let objToArr = [];

for (let [property, value] of Object.entries(obj)) {
for(var i=0; i<value; i++){
objToArr.push(property);
}
}
return objToArr;
}

console.log(arrayBuilder({watches: 3, rings: 1}));

关于javascript - 如何根据动态变量将元素插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53677723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com