gpt4 book ai didi

javascript - 将数组的元素转换为对象/Javascript

转载 作者:行者123 更新时间:2023-11-30 20:23:33 26 4
gpt4 key购买 nike

我在 JS 中创建一个简单的 Notes 管理器面临挑战,我编写了一个函数,它接受 one 字符串,给它和 id 并将其推送到一个笔记数组。

let nextId = 0;
const getId = () => nextId++;
let notes = [{id: getId(), value: 'Note'}];

const addNote = (input) => {
notes.push({id:getId(), value: input});
console.log('Note added');

我现在正在为一个将多个字符串作为参数的函数而苦恼

('own', 'snail', 'platypus')

为每个具有 id/value(string) 的元素创建一个对象,并将其推送到主数组。

结果应该是这样的:

[{ id: 1, value: 'owl'},
{ id: 2, value: 'snail'}]

到目前为止我有这个,它正确地分配了 ID,但是循环失败了

const batchAddNotes = (values) => {
let obj = {};
for (i = 0; i < values.length; i++) {
obj.id = (getId());
obj.value = (values[i]);}
return obj;};

最佳答案

为了让您的变量在某个范围内,我会将其全部打包到一个类(或一个函数)中。当您使用箭头函数时,该类应该没问题。按照您显示的方式添加多个节点;使用 var-args,您可以创建一个方法,该方法需要那些带有 (...input)

的方法

class Notes {
constructor() {
this.nextId = 0;
this.nodes = [{
id: this.getId(),
value: 'Note'
}];
}

addNote(input) {
this.nodes.push({
id: this.getId(),
value: input
})
}

getId() {
return this.nextId++;
}

addNotes(...input) {
input.forEach(e => this.addNote(e));
}
}

const notes = new Notes();
notes.addNotes('own', 'snail', 'platypus');
console.log(notes.nodes);

关于javascript - 将数组的元素转换为对象/Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51193476/

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