gpt4 book ai didi

Javascript - 将数组插入字典中

转载 作者:行者123 更新时间:2023-12-01 00:26:50 25 4
gpt4 key购买 nike

我对 JavaScript 还很陌生,而且我似乎无法让字典等基本的东西发挥作用。

这是我的代码:

    var dictio = {};
for(var i=0; i<2; i++)
{
var arra = [];
arra.push(
{
x: i,
y: i+10,
});

arra.forEach((element, index, array) => {
console.log("Iteration (X, Y): "+element.x+", "+element.y);
});

if(dictio[0])
{
var tempo = dictio[0];
console.log("Currently stored in the dictionary:")
tempo.forEach((element, index, array) => {
console.log("(X, Y): "+element.x+", "+element.y);
});
console.log("After adding arra to the dictionary:")
tempo.push(arra);
tempo.forEach((element, index, array) => {
console.log("New (X, Y): "+element.x+", "+element.y);
});
}
else
{
console.log("Created key+value");
dictio[0] = arra;
}
console.log("********************************");
}

输出如下所示:

:39 Iteration (X, Y): 0, 10
:57 Created key+value
:65 ********************************
:39 Iteration (X, Y): 1, 11
:45 Currently stored in the dictionary:
:47 (X, Y): 0, 10
:49 After adding arra to the dictionary:
:52 New (X, Y): 0, 10
:52 New (X, Y): undefined, undefined
:65 ********************************

但是,我希望看到 1, 11 出现在第 52 行 0,10 之后。但我反而看到未定义,未定义。你能让我知道我在这里做错了什么吗?感谢您抽出时间。

最佳答案

只需按 tempo 推送 arra 的第一个元素即可。应该可以工作

tempo.push(arra[0]);

工作演示

var dictio = {};
for(var i=0; i<2; i++)
{
var arra = [];
arra.push(
{
x: i,
y: i+10,
});

arra.forEach((element, index, array) => {
console.log("Iteration (X, Y): "+element.x+", "+element.y);
});

if(dictio[0])
{
var tempo = dictio[0];
console.log("Currently stored in the dictionary:")
tempo.forEach((element, index, array) => {
console.log("(X, Y): "+element.x+", "+element.y);
});
console.log("After adding arra to the dictionary:")
tempo.push(arra[0]);
tempo.forEach((element, index, array) => {
console.log("New (X, Y): "+element.x+", "+element.y);
});
}
else
{
console.log("Created key+value");
dictio[0] = arra;
}
console.log("********************************");
}

关于Javascript - 将数组插入字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58907777/

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