开发者

how to get index of a string from a list?

I have a list like

_Value1 = "'apple','ball','开发者_JAVA百科cat'....so on";

If I know that apple exists in above list.How to get index of whole string from the list.Like apple should have the index 1, ball should have 2 and so on.

What is the javascript code for this stuff?


var _Value1 = "'apple','ball','cat'";

// split the string on ","
var values = _Value1.split(",");

// call the indexOf method
var index = values.indexOf("'apple'");

working example: http://jsfiddle.net/Yt5fp/


You can also do this check if it is an older browser and add the indexOf method if it doesn't exist

if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;
        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;
    };
}


Try using this trick:

_Array = eval("[" + _Value1 + "]");

(It will create object of array using JSON)


Assuming your strings (apple, ball, cat...) will not have a , in them:

You can split a string based on a delimiter:

var split = _values.split(",")

You will get an array of strings: {'apple', 'ball', 'cat'}

You can use the indexOf method in the array to find the position of an element:

split.indexOf('apple')

indexOf is not supported by IE. You can use the alternative in How to fix Array indexOf() in JavaScript for Internet Explorer browsers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜