我厌倦了有限的javascript数组函数,并希望编写一些我自己的便捷原型函数来执行Set Theory函数。
以下是我迄今为止的代码
<script type="text/javascript">
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
Array.prototype.getIndices = function(obj){
var indices = new Array();
var i = this.length;
while (i--) {
if(this[i] === obj){
indices.push(i);
}
}
return indices;
}
Array.prototype.Union = function(arr){
//combines two arrays together to return a single array containing all elements (once)
//{1,2,3,4,5}.Union({3,4,5,6,7})
//returns: {1,2,3,4,5,6,7}
var primArray = this;
var secondArray = arr;
var i = primArray.length;
while(i--){
if(secondArray.contains(primArray[i])){
primArray.splice(i, 1);
}
}
var returnArr = primArray.concat(secondArray);
return returnArr;
}
Array.prototype.Intersection = function(arr){
//Returns an array of elements that are present in both sets
//{1,2,3,4,5}.Intersection({3,4,5,6,7})
//returns: {3,4,5}
var primArray = this;
var secondArray = arr;
var returnArr = new Array;
var i = 0;
while(i++<primArray.length){
if(secondArray.contains(primArray[i])){
returnArr.push(primArray[i]);
}
}
return returnArr;
}
Array.prototype.Complement = function(arr){
//Returns an array of elements that are only in the primary (calling) element
//{1,2,3,4,5}.Complement({3,4,5,6,7})
//return: {1,2}
var primArray = this;
var secondArray = arr;
var i = primArray.length;
while(i--){
if(secondArray.contains(primArray[i])){
primArray.splice(i, 1);
}
}
return primArray;
}
Array.prototype.SymmetricDifference = function(arr){
//Returns elements that are exclusive to each set
//{1,2,3,4,5}.SymmetricDifference({3,4,5,6,7})
//return: {1,2,6,7}
var primArray = this;
var secondArray = arr;
var i = primArray.length;
while(i--){
if(secondArray.contains(primArray[i])){
var indices = secondArray.getIndices(primArray[i]);
primArray.splice(i, 1);
var j=indices.length;
while(j--){
secondArray.splice(indices[j], 1);
}
}
}
var returnArr = primArray.concat(arr);
return returnArr;
}
function run(){
var Q = "A";
var D = [1,2,3,4,5,6,7,8,9,10];
var sets = {
"A":[1,2,3],
"B":[3,4,5],
"C":[5,6,7]
}
var R = D;
for(var el in sets){
R = R.Complement(sets[el]);
}
//if I alert D at this point I get 8,9,10 instead of 1,2,3,4,5,6,7,8,9,10 as I would expect? What am I missing here... It causes a problem when I perform D.Complement(R) later on
document.write(R + "<br/>");
R = R.Union(sets[Q]);
document.write(R + "<br/>");
//Here!
R = D.Complement(R);
document.write(R);
}
</script>
</head>
<body onload="run()">
</body>
</html>
当我尝试获取域的补充和我新构建的集合时,一切都在努力到最后一点。我预计将获得[1,2,3,4,5,6,7,8,9,10]和[8,9,10,1,2,3]的补充,这将产生[4, 5,6,7]但是当我执行D.Complement(R)时,我的D变量似乎变成了[1,2,3]。这似乎发生在我执行的枚举之后。
我认为可能是因为我在我的函数中使用this.splice和arr.splice,当我将变量传递给函数时,它们作为指针传递,这意味着我实际上正在处理实际的内存位置。所以我然后使用primArray和secondArray来创建一个副本来处理...但问题仍在发生
非常感谢
答案 0 :(得分:1)
所以我然后使用primArray和secondArray来创建一个副本来处理...但问题仍在发生
只是将它分配给一个变量并不会使它成为一个新数组,你仍然在处理传入的数组。你必须手动制作一个新的数组副本,方法是循环遍历它并复制每个索引或者通过加入和分裂。