Javascript数组反向功能意外行为 [英] Javascript array reverse function unexpected behavior

查看:51
本文介绍了Javascript数组反向功能意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解为什么情况1和情况2无法返回相同的结果.

I would like to understand why situation 1 and situation 2 don't return the same results.

情况1:

var array1 = ["1", "2", "3"];
var array2 = array1.reverse();

console.log(array1); // ["3", "2", "1"]
console.log(array2); // ["3", "2", "1"] Why this doesn't work ?

情况2:

var array1 = ["1", "2", "3"];
var array2 = array1;

console.log(array1);           // ["1", "2", "3"]
console.log(array2.reverse()); // ["3", "2", "1"] Why this works ?

推荐答案

情况1

reverse方法将调用数组对象的元素转置到位,变异该数组,并返回对该数组的引用.

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

情形2 中,您具有相同参考.您要在之前反转 array1 数组.

In Situation 2 you have the same reference. You are printing array1 array before reverse it.

var array1 = ["1", "2", "3"];
var array2 = array1;

console.log(array1);           // [ '1', '2', '3' ]
console.log(array2.reverse()); // [ '3', '2', '1' ]
console.log(array1);           // [ '3', '2', '1' ]

这篇关于Javascript数组反向功能意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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