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

What do return -1, 1, and 0 mean in this Javascript code? - Stack Overflow

programmeradmin38浏览0评论

Here is the context:

function compare (value1, value2) {
    if(value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {
        return 0;
    }
}

var values = [0, 6, 8, 5];
values.sort(compare);
alert(values); // 0,5,6,8

does -1 return the last argument? Like when using -1 in an array?

Here is the context:

function compare (value1, value2) {
    if(value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {
        return 0;
    }
}

var values = [0, 6, 8, 5];
values.sort(compare);
alert(values); // 0,5,6,8

does -1 return the last argument? Like when using -1 in an array?

Share Improve this question edited Jan 6, 2012 at 5:21 Hal 1,0091 gold badge11 silver badges22 bronze badges asked Nov 27, 2011 at 0:44 BriefbreadddBriefbreaddd 3792 gold badges3 silver badges12 bronze badges 1
  • Accessing arguments by index looks like arguments[0], and it won't accept negative numbers. – RightSaidFred Commented Nov 27, 2011 at 0:55
Add a comment  | 

4 Answers 4

Reset to default 26

No, -1, 0, and 1 in a comparison function are used to tell the caller how the first value should be sorted in relation to the second one. -1 means the first goes before the second, 1 means it goes after, and 0 means they're equivalent.

The sort function uses the comparisons in the function you pass it to sort the function. For instance, if you wanted to sort in reverse order, you could make line 3 return 1; and line 5 return -1.

The sort method takes an optional comparison function that determines the resulting sort order based on the following:

  • if its return value is less than zero, then sort value1 to a lower index than value2
  • if its return value is zero, then leave the indices of value1 and value2 unchanged with respect to each other
  • if its return value is greater than zero, then sort value1 to a higher index than value2

Note that given these rules, it's possible to shorten your comparison function to the following:

function compare(value1, value2) {
    return value1 - value2;
}

-1 means that value1 is less than value2

0 means that value1 is equal to value2

1 means that value1 is greater than value2

// filter in array
function filterDataByInput(){
    let searchInput = document.getElementById('searchInput').value;
    let result = userDetails.filter(function (value){
        return value.name.toLowerCase().indexOf(searchInput.toLowerCase()) > -1;
    });
    console.log(result)
}

-1 search from abcd 0 search from abcd 1 search from abcd

发布评论

评论列表(0)

  1. 暂无评论