如何在Javascript中编写自链函数
现在,我想做的是编写一个如何在Javascript中编写自链函数,javascript,Javascript,现在,我想做的是编写一个Array.prototype函数union(Array\u to\u union),我想这样称呼它: var a = [1,2,3]; a.union([2,3,4]).union([1,3,4]) ...... 结果将是这些数组的并集,我想知道如何才能做到这一点 我只知道我应该使用Array.prototype.union=function(Array\u to\u union){….}这个怎么样: Array.prototype.union = function
Array.prototype
函数union(Array\u to\u union)
,我想这样称呼它:
var a = [1,2,3];
a.union([2,3,4]).union([1,3,4]) ......
结果将是这些数组的并集,我想知道如何才能做到这一点
我只知道我应该使用Array.prototype.union=function(Array\u to\u union){….}
这个怎么样:
Array.prototype.union = function (second) {
return second.reduce(function (array, currentValue) {
if (this.indexOf(currentValue) === -1) array.push(currentValue);
return array;
}, this).sort();
};
试验
结果
它还对数组进行排序,如注释中的示例所示。可以链接在一起的联合函数:
Array.prototype.union = function(array_to_union) {
for (i = 0; i < array_to_union.length; i++) {
this.push(array_to_union[i]);
}
return this;
}
var a = [1,2,3];
a.union([4,5,6]).union([7,8,9]);
Array.prototype.union=函数(数组到联合){
对于(i=0;i
注意:在这种情况下,union函数只在另一个数组上添加一个数组(不关心排序或不同的值)
JS处理了更多示例:您只需
返回union函数中的数组实例。@incutonez谢谢!但我对JS非常陌生,你能给我一些代码示例吗?“把代码放在这里”的问题对于堆栈溢出来说太广泛了。你需要先试试。union
函数应该做什么?已经有这样一个函数了,它叫concat()
@Kuan OK。我添加了一些代码来创建一个联合体。@非常感谢!这正是concat()
所做的。顺便说一句,我知道。询问者可能只需要一个如何使用Array.prototype的示例。“这个问题确实需要澄清。”林赛我同意。我已把这个问题标为问题的副本。
a = [1, 2, 3, 4]
Array.prototype.union = function(array_to_union) {
for (i = 0; i < array_to_union.length; i++) {
this.push(array_to_union[i]);
}
return this;
}
var a = [1,2,3];
a.union([4,5,6]).union([7,8,9]);