Javascript array.prototype 几乎到处都被打印

标签 javascript jquery arrays

由于我必须从数组中删除一些元素,因此我遵循了 stackoverflow 中找到的几段代码,并提出了这个:

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

但是,由于某些原因,每当某些内容与数组有关时,这段代码就会被打印到任何地方。

示例:

这段代码:

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

Scadenza.prototype.init = function() {
    this.promemoria = (this.promemoria == "")?("NO"):(this.promemoria);
    var gruppo = this.group; // convert array to string.
    this.group = "";
    for (var i in gruppo) {
        if (i != (gruppo.length - 1)) {
            this.group += gruppo[i] + ", ";
        }
        else {
            this.group += gruppo[i];
        }
    }
    alert(this.group);
};

这段代码应该将数组 this.group (临时存储在变量“gruppo”中)转换为字符串(我认为这很明显)。

当然,如果它的警报不是这样的话,它就可以很好地完成它的工作:

[DATA NEEDED]function (from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }

这段代码也通过 AJAX 请求发送到数据库,查询结果在所需的列,如下:

function (from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); },

我对这种情况的发生感到非常惊讶,但我完全不知道如何解决它。

加载页面或单击引发此事件的按钮时,没有收到任何错误警报。

有什么想法吗?

ps:不确定是否有帮助,但我正在使用 jQuery。

@评论:

普通的 for 循环实际上并不能解决这个问题:

Scadenza.prototype.init = function() {
    this.promemoria = (this.promemoria == "")?("NO"):(this.promemoria);
    var gruppo = this.group; // convert array to string.
    this.group = "";
    for (var i = 0; i < gruppo.length; i++) {
        if (i != (gruppo.length - 1)) {
            this.group += gruppo[i] + ", ";
        }
        else {
            this.group += gruppo[i];
        }
    }
    alert(this.group);
};

警报仍然相同。

最佳答案

正确使用for (var i=0; i<arr.length; i++)用于迭代数组的循环。 for in enumerations will enumerate prototype properties as well ,不要在数组上使用它们。你正在你的 init 中这样做方法为例。

顺便说一句,对于该任务,您要使用 .join 无论如何:

Scadenza.prototype.init = function() {
    if (this.promemoria == "")
        this.promemoria = "NO";
    this.group = this.group.join(", "); // convert array to string
    alert(this.group);
};

关于Javascript array.prototype 几乎到处都被打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18878347/

相关文章:

javascript - 如何使用创建的函数中的信息添加到新的 <p> 标记中

javascript - 如何使文本居中并保持左对齐?

C - 如何输入这一行

c++ - 我可以以这种方式将数组转换为指针并返回指向常量的指针吗?

javascript - 如何停止此代码中的事件冒泡?

javascript - 谁在 JavaScript 中通过嵌套对象进行映射并删除键值对

javascript - AngularJs:在不同的组/表单/div 中使用 TAB 键进行键盘导航

php - 检索数组的最后一个数字(不是索引)——PHP 和 MySQL

javascript - Vue 资源 - plugin.apply 不是函数

javascript - Wordpress,以正确的方式添加自定义脚本