Javascript jquery split() 和 indexOf 导致“对象不支持此属性或方法”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2608575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:07:51  来源:igfitidea点击:

jquery split() and indexOf results in "Object doesn't support this property or method"

javascriptjqueryasp.net-mvcarrayssplit

提问by chris

I have the following code:

我有以下代码:

var selected = $('#hiddenField').val().split(",");
...
if (selected.indexOf(id) > 0) {
   ... set value ...
}

I'm dynamically creating a CheckBoxList, and trying to remember the state of the checkboxes by putting the selected IDs into the hidden field.

我正在动态创建一个 CheckBoxList,并尝试通过将选定的 ID 放入隐藏字段来记住复选框的状态。

I get an error stating that "Object doesn't support this property or method". My assumption is that selected is an array, which should support indexOf. Is that incorrect?

我收到一条错误消息,指出“对象不支持此属性或方法”。我的假设是 selected 是一个数组,它应该支持 indexOf。那不正确吗?

回答by Nick Craver

There's an jQuery method to overcome the lack of indexOf(), you can use .inArray()instead:

有一个 jQuery 方法可以克服 缺少indexOf(),您可以.inArray()改用:

var selected = $('#hiddenField').val().split(",");
if ($.inArray(id, selected) > -1) {
   ... set value ...
}

jQuery.inArray()exists for just this reason...if you're including jQuery already, no need to write the function again. Note: This actually returns a number, like indexOf()would.

jQuery.inArray()就因为这个原因而存在...如果您已经包含 jQuery,则无需再次编写该函数。注意:这实际上返回一个数字,就像indexOf()那样。

回答by Matt

Based on your error message, I'm assuming this is coming from Internet Explorer.

根据您的错误消息,我假设这是来自 Internet Explorer。

Surprise! Internet Explorer (including version 8) does not support indexOf for arrays.

惊喜!Internet Explorer(包括版本 8)不支持数组的 indexOf。

Here is Firefox's implementationyou can use:

这是您可以使用的Firefox 实现

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

回答by Ivo Sabev

[].indexOf || (Array.prototype.indexOf = function(v,n){
  n = (n==null)?0:n; var m = this.length;
  for(var i = n; i < m; i++)
    if(this[i] == v)
       return i;
  return -1;
});