最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using indexOf() in JS - is it wise to negate null values and how? - Stack Overflow

programmeradmin0浏览0评论

When searching through an array how do we deal with white spaces? Do we say a search returns false if the user types in nothing (i.e. just presses enter) or types in a blank space?

test_pages=[
"Lorem Ipsum is simply dummy text of the printing and typesetting industry."
, 
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout", 
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable." 
]

var find=prompt("Enter a term");
find = find.toLowerCase();

for(i=0;i<test_pages.length;i++)
    {   
        // normalisation
        test_pages[i] = test_pages[i].toLowerCase();

        // use indexOf() to find the occurrences of pattern
        if(test_pages[i].indexOf(find)>=0)
        {
            alert("true");
            break;
        }
        else if(test_pages[i].indexOf(find)<0)
        {
            alert("false");
        }    
    }

When searching through an array how do we deal with white spaces? Do we say a search returns false if the user types in nothing (i.e. just presses enter) or types in a blank space?

test_pages=[
"Lorem Ipsum is simply dummy text of the printing and typesetting industry."
, 
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout", 
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable." 
]

var find=prompt("Enter a term");
find = find.toLowerCase();

for(i=0;i<test_pages.length;i++)
    {   
        // normalisation
        test_pages[i] = test_pages[i].toLowerCase();

        // use indexOf() to find the occurrences of pattern
        if(test_pages[i].indexOf(find)>=0)
        {
            alert("true");
            break;
        }
        else if(test_pages[i].indexOf(find)<0)
        {
            alert("false");
        }    
    }
Share Improve this question asked Nov 2, 2011 at 8:21 methuselahmethuselah 13.2k53 gold badges177 silver badges333 bronze badges 1
  • 2 You don't need that else if: if indexOf is not more than or equal to 0, then it's guaranteed to be less than 0! – Eric Commented Nov 2, 2011 at 8:26
Add a ment  | 

5 Answers 5

Reset to default 2

This is a design decision you will need to make; I don't believe there is any "right" or "wrong" answer here. But to help you analyze the code you've provided for the cases in question, you should consider:

"hello".indexOf("h")       => 0
"hello".indexOf("")        => 0
"hello".indexOf(undefined) => -1
"hello".indexOf(null)      => -1

Also consider that prompt returns empty string when left blank. So as your code stands, if the user enters nothing, your code will alert true.

Well you should validate the input and request that the user actually types something inside. If that isn't possible, either response is logical and it won't have any different impact on the user experience

Your logic is currently wrong. If the search term is in the second text, it will alert "false" then "true"

var test_pages = [
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", 
    "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout", 
    "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable." 
]

var find = prompt("Enter a term").toLowerCase();

if(find) {
    var found = false;
    for(i = 0; i < test_pages.length; i++) {           
        // use indexOf() to find the occurrences of pattern
        if(test_pages[i].toLowerCase().indexOf(find) >= 0) {
            found = true;
            break;
        }   
    }
    alert(found ? "true" : "false");
}
else {
    alert("I can't search for that!");
}

Well, if you want to prevent users from searching for blank spaces, then validate the input up-front.

If you want to take a "Genie in the Magic Lamp" approach, and give people literally what they ask even if the oute is a bit mischievous, then simply return true if the user searches for the space character and the string has one.

If you want the algorithm to silently ignore whitespace, then you could implement something like this in the alternative:

test_pages=[
"Lorem Ipsum is simply dummy text of the printing and typesetting industry."
, 
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout", 
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable." 
]

var find=prompt("Enter a term");
find = find.toLowerCase();

// The jQuery operations could be re-written using vanilla JavaScript, 
// if you don't have jQuery available for some reason.
$.each(test_pages, function(index, value) {
    token_array = value.split(" ");
    normalized_array = new Array();
    $.each(token_array, function(index, token) { 
        normalized_array.push(token.toLowerCase()); 
    });

    if( $.inArray( find, normalized_array ) { 
        alert("true");
        break;
    } else {
        alert("false");
    }    
});

This approach, putting the string tokens into an Array and then checking the array, gives you for free the "filtering" you might be looking for. Values such as empty-string, whitespace, etc are not placed into the token array... so they will quietly go un-found.

Another alternative, if you're only returning a true/false result, would be to keep the implementation you currently have... but strip out whitespace prior to using the indexOf function.

I think you can just judge if trim(the input message) is empty if it does you can jump the search method and return false

var test_pages = [
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", 
    "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout", 
    "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable." 
]

var find = prompt("Enter a term").toLowerCase(),
    Search = function(str){
        if(str && str.trim() != "") {
            for(i = 0; i < test_pages.length; i++) {           
                if(test_pages[i].toLowerCase().indexOf(str)  > -1) {
                    return true;
                }   
            }
        }
        return false;
    };
Search(find) ? alert("search it") : alert ("no search");
发布评论

评论列表(0)

  1. 暂无评论