我从allusers
获取了所有myfactory
数组:
$scope.allusers = myfactory.getFactoryOriginalAllUsers();
///[1,2,3]
$scope.allusers.splice(0,1);
///[2,3]
但是当我想要原来的
时$scope.allusers2 = myfactory.getFactoryOriginalAllUsers();
///[2,3]
为什么$scope.allusers2
与$scope.allusers
相同?它不应该与原始工厂副本[1,2,3]
相同吗?
如何保持原始工厂副本不受影响?
答案 0 :(得分:3)
js中的对象通过引用传递。这意味着您返回引用,而不是整个对象(或数组)。
如果要修改返回的对象,则必须手动复制它。
在您的情况下,您通常应该复制数组:
for(var i=0;i<array.length;i++)
{
newArray.push(array[i]);
}
但@bstockwell提供了一个很好的建议,你可以使用角度方法https://docs.angularjs.org/api/ng/function/angular.copy
答案 1 :(得分:1)
我正在使用这两个功能:
var getType = (function () {
var class2type = {},
toString = class2type.toString;
"Boolean Number String Function Array Date RegExp Object Error".split( " " ).forEach( function ( name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
return function ( obj ) {
if ( obj === null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj;
};
})();
/**
* will copy the object
* @param obj
* @param depth
* @returns {*}
*/
function copyObject( obj, depth ) {
depth = depth || 0;
if ( depth < 10 /* max depth */ ) {
if ( getType( obj ) === "object" ) {
var deepCopy = {};
var props = Object.getOwnPropertyNames( obj );
props.forEach( function ( it ) {
if ( getType( obj[ it ] ) === "object" ) {
deepCopy[ it ] = copyObject( obj[ it ], depth + 1 );
} else if ( getType( obj[ it ] ) === "array" ) {
deepCopy[ it ] = [];
obj[ it ].forEach( function ( x ) {
deepCopy[ it ].push( copyObject( x, depth + 1 ) );
} );
} else {
Object.defineProperty( deepCopy, it, Object.getOwnPropertyDescriptor( obj, it ) );
}
} );
return deepCopy;
}
}
return copy( obj );
}
/**
* copies object and returns new instance without references
* @param object
* @param copyProperties
* @returns object
*/
function copy( object, copyProperties ) {
if ( object === undefined ) {
return undefined;
} else if ( object === null ) {
return null;
} else if ( copyProperties ) {
if ( getType( object ) === "object" ) {
return copyObject( object );
} else if ( getType( object ) === "array" ) {
var list = [];
object.forEach( function ( it, i ) {
list[ i ] = copyObject( it );
} );
return list;
}
} else {
return JSON.parse( JSON.stringify( object ) );
}
}
使用return JSON.parse( JSON.stringify( object ) );
时,您将创建对象的快速副本,但会丢失definedProperties