JavaScript strcmp ()가 있습니까?
누구든지 나를 위해 이것을 확인할 수 있습니까? JavaScript에는 strcmp () 버전이 없으므로 다음과 같이 작성해야합니다.
( str1 < str2 ) ?
-1 :
( str1 > str2 ? 1 : 0 );
이건 어떤가요
str1.localeCompare(str2)
Javascript에는 지적한 바와 같이 없습니다.
빠른 검색이 이루어졌습니다.
function strcmp ( str1, str2 ) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// + input by: Steve Hilder
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: gorthaur
// * example 1: strcmp( 'waldo', 'owald' );
// * returns 1: 1
// * example 2: strcmp( 'owald', 'waldo' );
// * returns 2: -1
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
에서 http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/
물론 필요한 경우 localeCompare를 추가 할 수 있습니다.
if (typeof(String.prototype.localeCompare) === 'undefined') {
String.prototype.localeCompare = function(str, locale, options) {
return ((this == str) ? 0 : ((this > str) ? 1 : -1));
};
}
str1.localeCompare(str2)
로컬 브라우저와 함께 제공되는 것에 대해 걱정할 필요없이 어디서나 사용할 수 있습니다. 유일한 문제는 당신이 지원을 추가해야한다는 것입니다 locales
그리고options
당신이 그것에 대해 걱정합니다.
localeCompare()
느린 당신이 영어 이외의 문자 문자열의 "올바른"주문에 대한 관심이 원래의 방법 또는 시도하지 않는 그렇다면, 클리너 보이는 :
str1 < str2 ? -1 : +(str1 > str2)
이것은 localeCompare()
내 컴퓨터 보다 훨씬 빠릅니다 .
따라서 +
답변은 항상 부울이 아닌 숫자가됩니다.
var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;
용법: strcmp(string1, string2)
결과 : 1
string1이 더 크다는 0
의미, 같음, -1
string2가 더 크다는 의미.
이것은보다 성능이 높습니다 String.prototype.localeCompare
또한 numeric:true
논리 숫자 비교를 수행합니다.
어때요?
String.prototype.strcmp = function(s) {
if (this < s) return -1;
if (this > s) return 1;
return 0;
}
그런 다음 s1을 2와 비교하려면
s1.strcmp(s2)
참고 URL : https://stackoverflow.com/questions/1179366/is-there-a-javascript-strcmp
'Programming' 카테고리의 다른 글
.csproj 파일에서 (0) | 2020.07.11 |
---|---|
READ_COMMITTED_SNAPSHOT가 활성화되어 있는지 감지하는 방법은 무엇입니까? (0) | 2020.07.11 |
파이썬에서 상속 및 __init__ 재정의 (0) | 2020.07.11 |
파이썬에서 상속 및 __init__ 재정의 (0) | 2020.07.11 |
SSH 명령에 비밀번호를 제공하기 위해 bash 스크립트에서 expect 사용 (0) | 2020.07.11 |