最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I move an element from an array to another array in javascript? - Stack Overflow

programmeradmin1浏览0评论

My code is like

var shapes1 = [  r.image("node.gif",190, 100, 47, 45)];
var shapes2 =[];
for (var i = 0, ii = shapes1.length; i < ii; i++) {
    shapes1[i].mousedown(function(e){
        var temp=this.clone();
        shapes1.push(temp);
        //now I want to remove "this" from shapes1
        //and put it into shape2
        //HOW??
        isDrag=true;
        e.preventDefault();
    });
}

Maybe this is the wrong way to do it? I should be using a class instead, but isn't that for DOM items?

My code is like

var shapes1 = [  r.image("node.gif",190, 100, 47, 45)];
var shapes2 =[];
for (var i = 0, ii = shapes1.length; i < ii; i++) {
    shapes1[i].mousedown(function(e){
        var temp=this.clone();
        shapes1.push(temp);
        //now I want to remove "this" from shapes1
        //and put it into shape2
        //HOW??
        isDrag=true;
        e.preventDefault();
    });
}

Maybe this is the wrong way to do it? I should be using a class instead, but isn't that for DOM items?

Share Improve this question asked Mar 22, 2010 at 12:56 TiansHUoTiansHUo 8,6397 gold badges48 silver badges57 bronze badges 1
  • Maybe you should describe what exactly you are trying to do. – Gumbo Commented Mar 22, 2010 at 13:06
Add a ment  | 

2 Answers 2

Reset to default 3

I find it handy to have things like

function removeIf(arr, predicate) {

    for (var i = 0; i < arr.length; i++) {
        if (predicate(arr[i])) {
            arr.splice(i--, 1);
        }
    }
}

So then:

var shapes1 = [  r.image("node.gif",190, 100, 47, 45)];
var shapes2 =[];
for (var i = 0, ii = shapes1.length; i < ii; i++) {
    shapes1[i].mousedown(function(e){
        var temp=this.clone();
        shapes1.push(temp);

        removeIf(shapes1, function (item) { return item === this; });

        shapes2.push(this);

        isDrag=true;
        e.preventDefault();
    });
}

Use splice(index, range) to remove items from an array.

发布评论

评论列表(0)

  1. 暂无评论