Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用IE8中的Javascript将字符串拆分为数组_Javascript_Internet Explorer 8_Split_Indexof - Fatal编程技术网

使用IE8中的Javascript将字符串拆分为数组

使用IE8中的Javascript将字符串拆分为数组,javascript,internet-explorer-8,split,indexof,Javascript,Internet Explorer 8,Split,Indexof,我有一个字符串,需要用三个下划线字符分隔。字符串的一个示例可能是: var stringItemsPlanner = "Hello this___is a string___which___needs splitting into___an array"; 所以我使用Split()函数。除了IE8(也可能是7,但没有尝试过)之外,一切都很好,如果字符串不包含这些字符,IE8会给出“Object不支持此属性或方法”错误。所以我找到了另一篇帖子,上面说在拆分之前检查字符串中是否出现下划线字符,所以

我有一个字符串,需要用三个下划线字符分隔。字符串的一个示例可能是:

var stringItemsPlanner = "Hello this___is a string___which___needs splitting into___an array";
所以我使用Split()函数。除了IE8(也可能是7,但没有尝试过)之外,一切都很好,如果字符串不包含这些字符,IE8会给出“Object不支持此属性或方法”错误。所以我找到了另一篇帖子,上面说在拆分之前检查字符串中是否出现下划线字符,所以我这样做:

if (stringItemsPlanner.indexOf('___') == -1){
    arrItemsPlanner = [];
}else{
    arrItemsPlanner = stringItemsPlanner.split('___');
}
但现在这个错误也出现了,因为显然IE8不支持'indexOf'

经过大量搜索后,我尝试在脚本顶部添加一些代码,作为此方法的“polyfil”:

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;
      };
    }
  }
}
if(!Array.prototype.indexOf){
Array.prototype.indexOf=函数(elt/*,from*/){
var len=this.length>>>0;
var from=Number(参数[1])| | 0;
from=(from<0)?Math.ceil(from):Math.floor(from);
如果(从<0开始){
from+=len;
for(;from
但仍然没有快乐

我现在已经过了沮丧的地步,真的想不出任何其他方法来让这件简单的事情起作用

有人能解释一下这一点吗?有人能想出另一种方法,以跨浏览器的方式将字符串安全地拆分为数组吗?这必须很简单,但我现在不能直接思考

谢谢大家

看看这里


您完全确定
split
在IE8中不起作用吗?(我刚刚在IE9中的“IE8模式”中尝试了它,也在“IE7模式”中尝试了它,似乎还可以)IE8中应该支持split()。对不起,我现在已经说得更清楚了。IE8支持拆分,但如果要拆分的字符串中没有字符,则会引发异常-在我的情况下可能会发生这种情况,这就是问题的原因。如果字符串不包含要查找的针,则拆分只返回-1。我认为它不应该抛出异常。字符串是字符串而不是数组
Array.prototype.indexOf
满足您可以使用的
[].indexOf()
。ECMAScript 1.0-IE8是否明确支持它-
var stringItemsPlanner = "Hello this___is a string___which___needs splitting into___an array";

var arrItemsPlanner = (stringItemsPlanner.length==0 || stringItemsPlanner.indexOf('___') == -1)? []:stringItemsPlanner.split('___');

alert(arrItemsPlanner.join('\n'))