雄辩的javascript练习4.2反转数组
在下面的代码中,我不理解为什么reverseArrayOne与reverseArrayTwo相比不返回反向数组。本质上,我相信在这两种情况下,我都将反向数组分配给数组。链接到问题雄辩的javascript练习4.2反转数组,javascript,arrays,arguments,global-variables,scoping,Javascript,Arrays,Arguments,Global Variables,Scoping,在下面的代码中,我不理解为什么reverseArrayOne与reverseArrayTwo相比不返回反向数组。本质上,我相信在这两种情况下,我都将反向数组分配给数组。链接到问题 将数组传递给函数时,函数可能会更改数组本身的值 ReverseArrayValue返回一个反向数组,但不更改arrayValue的值 reverseArrayTwoarrayValue实际上会更改arrayValue的值,因为函数中有这一行: array[i] = reversedArray[i]; 在日志中,显示的
将数组传递给函数时,函数可能会更改数组本身的值 ReverseArrayValue返回一个反向数组,但不更改arrayValue的值 reverseArrayTwoarrayValue实际上会更改arrayValue的值,因为函数中有这一行:
array[i] = reversedArray[i];
在日志中,显示的是arrayValue的值,而不是函数返回的结果
console.log(arrayValue)
第一个函数不更改数组值,因此它将返回[1,2,3,4,5]。第二个函数实际上更改了数组值,因此它将返回[5,4,3,2,1]。如果您只需要打印数组的反面,那么应该这样做
result = reverseArrayOne(arrayValue);
console.log(result)
请记住如何对待和与值不同的区别。我已经添加了一些注释来解释这个过程,如果您需要更多详细信息,请点击答案 一个主要区别是: 虽然对象是通过引用传递的,但后者是通过值传递的
function reverseArray(array) {
reversedArray = [];
for (i=array.length-1; i>=0; i--) {
reversedArray.push(array[i]);
}
//return a new array with elements in a reverse order of original array
return reversedArray;
}
function reverseArrayOne(array) {
//scope of object reference is in the function only and hence is not reflected outside
array = reverseArray(array);
//return the same object pointer which now points to a new array
return array;
}
function reverseArrayTwo(array) {
reversedArray = reverseArray (array);
for (i=0; i<reversedArray.length; i++) {
//you are changing the properties of the same object(this is different from merely changing the reference of the object)
array[i] = reversedArray[i];
}
return array;
}
var arrayValue = [1, 2, 3, 4, 5];
//passing arrayValue as reference
reverseArrayOne(arrayValue);
//original arrayValue still points to the original array since the reverse value is not in scope.
console.log(arrayValue);
// → [1,2,3,4,5]
reverseArrayTwo(arrayValue);
//the original array is the same,but the internal property of the object has been changed and hence is reflected
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
我认为这可能是一个很好的方法
var list = ["orange", "apple", "pear"]
var newList = [];
function newReverse(list){
for(var i=0; i<list.length; i++){
newList.push(list[i]);
}
newList.reverse();
return newList;
}
这个练习很愚蠢,因为你可以只使用Array.reverse。看这里-@adeneo:这是一个练习。为什么Array=reverseArrayarray不更改数组的值,而Array[i]=reversedArray[i]更改数组的值?@user3812377:第一个更改数组变量,而第二个更改数组引用的数组对象。
var list = ["orange", "apple", "pear"]
var newList = [];
function newReverse(list){
for(var i=0; i<list.length; i++){
newList.push(list[i]);
}
newList.reverse();
return newList;
}