【问题标题】:How do I move an element from an array to another array in javascript?如何在javascript中将元素从数组移动到另一个数组?
【发布时间】:2010-03-22 12:56:56
【问题描述】:

我的代码是这样的

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();
    });
}

也许这是错误的做法?我应该改用一个类,但这不是用于 DOM 项吗?

【问题讨论】:

  • 也许你应该描述一下你到底想要做什么。

标签: javascript arrays move


【解决方案1】:

我觉得有类似的东西很方便

function removeIf(arr, predicate) {

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

那么:

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();
    });
}

【讨论】:

  • 没问题。传入一个函数来测试每个项目的好处是,您可以使用它根据您想要的任何“查询”删除多个项目,例如而不是item === this 它可以是item.firstName.length &gt; item.lastName.length 删除任何firstName 长于lastName 的项目(好吧,这只是一个愚蠢的例子,但你会看到它有多强大)。
【解决方案2】:

使用 splice(index, range) 从数组中删除项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2023-03-29
    相关资源
    最近更新 更多