未引用数组没有那么未引用后"切片"? [英] Unreferenced Array not so Unreferenced after "slice"?

查看:81
本文介绍了未引用数组没有那么未引用后"切片"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这不是常见的数组复制问题,其中使用 arr.slice(0)以百万计的DUP之一修复了这个问题

Note: this isn't one of the millions dups of the common array copy 'problem' where using arr.slice(0) fixes this 'problem'

不过,我想知道为什么我得到这个意外的结果:

That said, I want to understand why I am getting this unexpected result:

var oldArr = [[1,2],[3,4]];
var find = oldArr[1];

var newArr = oldArr.slice(0);
console.log(newArr.indexOf(find)); //1?

//proof that newArr is NOT referenced to oldArr
newArr[0] = "Hi";
newArr[1] = "How are you?";
console.log(oldArr+" "+newArr); //"1,2,3,4 Hi,How are you?"

jsFildde演示

如果您替换找到与下列任何的替代品,它返回预期的 1

If you replace find with any of the following alternatives, it returns the expected -1:


  • 使用 [3,4] 直接

  • 使用一个变量控股 [3,4]

  • 使用一个变量与另一个数组持有参考 [3,4]

  • Use [3,4] directly
  • Use a variable holding [3,4]
  • Use a variable with reference of another array holding [3,4]

我找不到为什么会有这些过去三个方法与第一个例子之间的差异作出任何解释。据我所知,不应该有任何。

I can't find any explanation on why there is any difference between these last three methods and the first example. As far as I know, there shouldn't be any.

任何想法?

推荐答案

[[1,2],[3,4]]

三数组对象创建。

只有外层正在'D。这将导致一个浅拷贝。

Only the outer one is being slice'd. This results in a "shallow copy".

考虑一下:

var a = [1,2]
var b = [3,4]
var c = [a,b]
var d = c.slice(0)
d[0] === a       // true, which means it is the /same/ object
d[0][0] = "Hi!"
a                // ["Hi!", 2]

编程快乐!

这篇关于未引用数组没有那么未引用后"切片"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆