Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否创建编辑原始数组而不是返回新数组的方法?_Javascript - Fatal编程技术网

Javascript 是否创建编辑原始数组而不是返回新数组的方法?

Javascript 是否创建编辑原始数组而不是返回新数组的方法?,javascript,Javascript,我想知道如何做上述 通过对原始数组应用方法来编辑该数组。到目前为止,我想我能做的就是: Array.prototype.foo = function() { this = [ "random", "static", "replacement" ]; } originalArray = [ "this", "was", "here", "first" ]; originalArray.foo(); console.log( originalArray ); // [ "random"

我想知道如何做上述

通过对原始数组应用方法来编辑该数组。到目前为止,我想我能做的就是:

Array.prototype.foo = function() {
    this = [ "random", "static", "replacement" ];
}

originalArray = [ "this", "was", "here", "first" ];

originalArray.foo();

console.log( originalArray ); // [ "random", "static", "replacement" ];
可以使用.splice()修改数组

Array.prototype.foo = function() {
    this.length = 0; //this clears the array
    this.push("random"); 
    this.push("static"); 
    this.push("replacement");
}

删除原始数组,然后使用
push

Array.prototype.foo = function() {
    this.splice(0,this.length,"random","static","replacement");
}
正如volune所说,如果输入是一个数组,则可以使用该函数

Array.prototype.foo = function() {
    this.length = 0;
    this.push( "random", "static", "replacement" );
}

xyz=…
这样的赋值在JS中从不修改
xyz
下的对象,它只是使
xyz
变量指向另一个对象。因此,真的没有直接的方法让方法改变它应用到的“对象”的值吗?你甚至可以做
this.push.apply(这是参数)
@user3387566我不这么认为,即使分配给
这个
也是一个语法错误。谢谢大家。我更喜欢这个答案,但我假设,因为我的方法基于原始数组计算新数组,所以我必须使用for循环将新数组值推送到原始数组中。@user3387566您不需要for循环,我根据volune的建议更新了答案。
Array.prototype.foo = function() {
    this.length = 0;
    this.push( "random", "static", "replacement" );
}
Array.prototype.foo = function() {
    this.length = 0;
    var newArray = ["random", "static", "replacement"];
    this.push.apply(this, newArray);
}