Implementation of JAVA-compatible hashCode algorithm code in javascript

Source: Internet
Author: User
This article mainly introduces how to share the JAVA-compatible hashCode algorithm code in javascript to achieve the same operation result as that in JAVA. If you need it, you can refer to a hashCode Algorithm in java, it can be used to calculate the hash value of a string. Today, a friend suddenly asked me if he could calculate the hashCode in js, which requires the same calculation result as that in java.

I have never understood java's hashCode algorithm before, but I guess it should not be too difficult. So now I have written this code in java for testing:
Result: 899755

Press Ctrl and click the hashCode method name to check its algorithm. The Code is as follows:

The Code is as follows:


Public int hashCode (){
Int h = hash;
If (h = 0 ){
Int off = offset;
Char val [] = value;
Int len = count;

For (int I = 0; I <len; I ++ ){
H = 31 * h + val [off ++];
}
Hash = h;
}
Return h;
}

This is good. It should be okay to simply port it to js. Write the following JS Code:

The Code is as follows:


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.