英文:
Javascript Spread operator confusing behavior
问题
我不知道如何在标题中键入它,如果有重复,请告诉我,因为我对应该搜索什么关键字感到困惑。
基本上,我遇到了一个问题,或者对JavaScript或TypeScript的“展开运算符”行为感到困惑。我今天在处理拖放功能时偶然遇到了这个问题,但我会为您提供一个简单的示例来说明这个问题。假设我有一个简单的数组,像这样:
test = [
{
name: 'A',
id: 1
},
{
name: 'B',
id: 1
},
{
name: 'C',
id: 3
},
{
name: 'D',
id: 4
},
{
name: 'E',
id: 5
},
]
假设我想对数组进行浅拷贝,一开始我是这样做的,因为这对我来说是本能的,直到我重新检查代码才意识到。
我对它的第一段代码如下:
const tempArray = { ...test }
console.log('检查数据:', tempArray) // 将得到一个数组
如果你看我的代码,它使用{}
或Object
作为封装方法,对吗?但我没有意识到,因为它能显示出一个数组,但当我重新检查并将其更改为这样时:
const tempArray = [...test]
console.log('检查数据:', tempArray) // 将得到一个数组,因为它使用了字面数组
它仍然是正确的,显示了一个对象数组。你能告诉我我们称这种行为为什么,这样我以后可以搜索并解释为什么它显示相同的正确结果吗?是因为它将对象转换为数值数组,但在控制台上没有显示出来,还是有其他解释?
英文:
I don't know how to type it on the title, and if by any chance it duplicated please tell me about it since I'm confused as what keyword I must search for this problem.
basically I have a problem or got confused with javascript or typescript spread operator
behavior. I stumbled this problem just today when working with drag and drop function, but I will give you a simple example for this issue. let say I have a simple array like this
test = [
{
name: 'A',
id: 1
},
{
name: 'B',
id: 1
},
{
name: 'C',
id: 3
},
{
name: 'D',
id: 4
},
{
name: 'E',
id: 5
},
]
let say I want to make a shallow copy for the array, at first I'm doing it like this because it reflex for me and I not realized it until I do a recheck for my code.
my first code for it:
const tempArray = { ...test }
console.log('cek data : ', tempArray) // will result on array
if you see on my code it using {}
or Object
as the capsulating method right? but I don't realize it because it works showing an array for me, but when I do recheck and change it into this
const tempArray = [...test]
console.log('cek data : ', tempArray) // will result on array since it using literal array
and it still correct and showing an array of object, can you tell me what we called this behavior so I can search it later and explain why this is showing the same correct result? is it because it make it object into array numeric but not showing it on console or any other explanation for this?
EDIT 1:
ah I see thanks for pointing out, when I check it again yeah it show a different result, I missed it because it looks the same but as you can see on the image the object one make it looks like an array but in fact it makes an object by adding number as its key
答案1
得分: 2
以下是您要翻译的内容:
看起来您对第一个输出有误解。
运行此代码会生成一个对象,其中输入数组的索引作为键,数组的值作为值。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论