返回没有删除元素的数组?使用splice()而不更改数组? [英] Returning an array without a removed element? Using splice() without changing the array?

查看:244
本文介绍了返回没有删除元素的数组?使用splice()而不更改数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情:

var myArray = ["one","two","three"];
document.write(myArray.splice(1,1));
document.write(myArray);

因此它首先显示一,三",然后显示一,二,三".我知道splice()返回删除的元素并更改数组,但是有没有函数返回删除了元素的新数组?我试过了:

So that it shows first "one,three", and then "one,two,three". I know splice() returns the removed element and changes the array, but is there function to return a new array with the element removed? I tried:

window.mysplice = function(arr,index,howmany){
    arr.splice(index,howmany);
    return arr;   
};

如果我尝试:

var myArray = ["one","two","three"];
document.write(mySplice(myArray,1,1));
document.write(myArray);

它仍然会更改myArray ...

It still changes myArray...

请帮助.

推荐答案

如以下答案所示,这是代码快照

as suggested by the answer below, here is a code snapshot

var myArray = ["one", "two", "three"];
var cloneArray = myArray.slice();

myArray.splice(1, 1);

console.log(myArray);
console.log(cloneArray);

这篇关于返回没有删除元素的数组?使用splice()而不更改数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆