为了账号安全,请及时绑定邮箱和手机立即绑定

我发现concat与unshift有一些微妙的差异,不知道为什么... ...

我发现concat与unshift有一些微妙的差异,不知道为什么... ...

倚天杖 2023-02-11 17:13:25
1)下面第二行,需要对hello进行重新赋值,不然第三行document.write的结果会是abcde没有f,g也没有x和y,请问这是为什么?var hello=['a','b','c','d','e','f','g'];hello=hello.concat(['x','y']);document.write(hello);2)下面第二行如果对hello重新赋值的话,document.write结果不是0abcdefg,而是8,请问这是为什么?var hello=['a','b','c','d','e','f','g'];hello = hello.unshift('0');document.write(hello);3)unshift和concat都是控制数列的固有函数,但为什么在这里会有差异?
查看完整描述

2 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

<script type="text/javascript">
var arr=['a','b','c','d','e','f','g'];
arr.concat(['x','y']);
alert(arr.concat(['x','y']));
alert(typeof(arr.concat(['x','y'])));
document.writeln(arr);
document.write(arr.concat('x','y'));
</script>

<script type="text/javascript">
var arr=['a','b','c','d','e','f','g'];
arr.unshift('0');
alert(arr);
alert(typeof(arr.unshift('0')));
document.writeln(arr);
document.writeln(arr.unshift('0'));
</script>

我自己做了实验,总结出你自己没有好好区分数组和数组.方法()。第一个concat,也不需要对hellow从新赋值,你要么直接输出arr.concat('x','y').要么重新定义一个数组来存放结果。
第二个arr是数组,arr.unshift('0')是数组方法返回的是个number。

 


查看完整回答
反对 回复 2023-02-15
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

  1. var hello=['a','b','c','d','e','f','g'];

    > undefined

    hello.concat(['x','y']);

    > ["a", "b", "c", "d", "e", "f", "g", "x", "y"]

    hello

    > ["a", "b", "c", "d", "e", "f", "g"]

  2. 综上:concat 是连接之后的新的数组,但是不会修改原始数组,

    原始数组不发生变化。这个是我在浏览器控制台打印的信息,和你的表述不同

  3. unshift返回的是被修改后的数组的长度,所以是8


查看完整回答
反对 回复 2023-02-15
  • 2 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信