질문자 :Daniel Schaffer
Javascript에 null 병합 연산자가 있습니까?
예를 들어 C#에서는 다음과 같이 할 수 있습니다.
String someString = null; var whatIWant = someString ?? "Cookies!";
Javascript에 대해 알아낼 수 있는 가장 좋은 근사값은 조건부 연산자를 사용하는 것입니다.
var someString = null; var whatIWant = someString ? someString : 'Cookies!';
이것은 일종의 icky IMHO입니다. 내가 더 잘할 수 있을까?
업데이트
JavaScript는 이제 nullish 병합 연산자(??)를 지원합니다. 왼쪽 피연산자가 null
이거나 undefined
경우 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환합니다.
사용하기 전에 호환성을 확인하십시오.
C# null 병합 연산자( ??
)에 해당하는 JavaScript는 논리적 OR( ||
)을 사용합니다.
var whatIWant = someString || "Cookies!";
동작이 C#의 동작과 일치하지 않는 경우(아래에 설명됨)가 있지만 이것은 JavaScript에서 기본/대체 값을 할당하는 일반적이고 간결한 방법입니다.
설명
첫 번째 피연산자의 유형에 관계없이 부울로 캐스팅하면 false
가 발생하면 할당에서 두 번째 피연산자를 사용합니다. 아래의 모든 경우에 주의하십시오.
alert(Boolean(null)); // false alert(Boolean(undefined)); // false alert(Boolean(0)); // false alert(Boolean("")); // false alert(Boolean("false")); // true -- gotcha! :)
이것은 다음을 의미합니다.
var whatIWant = null || new ShinyObject(); // is a new shiny object var whatIWant = undefined || "well defined"; // is "well defined" var whatIWant = 0 || 42; // is 42 var whatIWant = "" || "a million bucks"; // is "a million bucks" var whatIWant = "false" || "no way"; // is "false"
Community Wikifunction coalesce() { var len = arguments.length; for (var i=0; i<len; i++) { if (arguments[i] !== null && arguments[i] !== undefined) { return arguments[i]; } } return null; } var xyz = {}; xyz.val = coalesce(null, undefined, xyz.val, 5); // xyz.val now contains 5
이 솔루션은 SQL 병합 기능과 같이 작동하며 임의의 수의 인수를 허용하고 값이 없는 경우 null을 반환합니다. 그것은 C#처럼 동작합니까 ?? "", false 및 0은 NOT NULL로 간주되므로 실제 값으로 계산된다는 점에서 연산자입니다. .net 배경에서 온 경우 이것이 가장 자연스러운 느낌의 솔루션이 될 것입니다.
Brent Larsen예, 곧 출시될 예정입니다. 여기에서 제안을 참조 하고 여기에서 구현 상태를 확인하세요 .
다음과 같습니다.
x ?? y
예시
const response = { settings: { nullValue: null, height: 400, animationDuration: 0, headerText: '', showSplashScreen: false } }; const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default' const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default' const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: '' const animationDuration = response.settings?.animationDuration ?? 300; // result: 0 const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false
vaughan만약 ||
C#의 대체품으로 ??
빈 문자열과 0을 삼키기 때문에 귀하의 경우에는 충분하지 않으므로 항상 자신의 함수를 작성할 수 있습니다.
function $N(value, ifnull) { if (value === null || value === undefined) return ifnull; return value; } var whatIWant = $N(someString, 'Cookies!');
sthNaN
의 가능성에 대해 언급하지 않았으며, 이는 나에게 있어서도 null 값입니다. 그래서 2센트를 더해야겠다고 생각했습니다.
주어진 코드의 경우:
var a, b = null, c = parseInt('Not a number'), d = 0, e = '', f = 1 ;
||
연산자를 사용하면 거짓이 아닌 첫 번째 값을 얻습니다.
var result = a || b || c || d || e || f; // result === 1
여기에 게시된 일반적인 병합 방법을 사용하면 NaN
값을 갖는 c
를 얻을 수 있습니다.
var result = coalesce(a,b,c,d,e,f); // result.toString() === 'NaN'
이 중 어느 것도 나에게 옳지 않은 것 같습니다. 여러분의 세계와 다를 수 있는 병합 논리의 작은 세계에서 저는 undefined, null 및 NaN을 모두 "null-ish"로 간주합니다. d
(영)를 반환할 것으로 예상합니다.
누군가의 두뇌가 나와 같이 작동하고 NaN
을 제외하려는 경우 이 방법으로 다음을 수행할 수 있습니다.
function coalesce() { var i, undefined, arg; for( i=0; i < arguments.length; i++ ) { arg = arguments[i]; if( arg !== null && arg !== undefined && (typeof arg !== 'number' || arg.toString() !== 'NaN') ) { return arg; } } return null; }
코드를 가능한 한 짧게 하고 약간의 명확성 부족에 신경쓰지 않는 사람들을 위해 @impinball이 제안한 대로 이것을 사용할 수도 있습니다. 이것은 NaN이 NaN과 결코 같지 않다는 사실을 이용합니다. 자세한 내용은 여기에서 읽을 수 있습니다. NaN이 NaN과 같지 않은 이유는 무엇입니까?
function coalesce() { var i, arg; for( i=0; i < arguments.length; i++ ) { arg = arguments[i]; if( arg != null && arg === arg ) { //arg === arg is false for NaN return arg; } } return null; }
Kevin Nelson논리적 무효 할당, 2020+ 솔루션
새로운 연산자가 현재 브라우저에 추가되고 있습니다. ??=
이것은 null 병합 연산자 ??
할당 연산자 =
.
참고: 이는 아직 공용 브라우저 버전에서는 일반적이지 않습니다. 가용성이 변경되면 업데이트됩니다.
??=
변수가 정의되지 않았거나 null인지 확인하고 이미 정의된 경우 단락됩니다. 그렇지 않은 경우 오른쪽 값이 변수에 할당됩니다.
기본 예
let a // undefined let b = null let c = false a ??= true // true b ??= true // true c ??= true // false
객체/배열 예제
let x = ["foo"] let y = { foo: "fizz" } x[0] ??= "bar" // "foo" x[1] ??= "bar" // "bar" y.foo ??= "buzz" // "fizz" y.bar ??= "buzz" // "buzz" x // Array [ "foo", "bar" ] y // Object { foo: "fizz", bar: "buzz" }
브라우저 지원 '21년 4월 - 84%
모질라 문서
Gibolt설명을 읽은 후 @Ates Goral의 답변은 JavaScript의 C#에서 수행하는 것과 동일한 작업을 수행하는 방법을 제공합니다.
@Gumbo의 대답은 null을 확인하는 가장 좋은 방법을 제공합니다. 그러나 특히 undefined
및/또는 null
검사 문제와 관련하여 JavaScript ==
대 ===
의 차이점에 주목하는 것이 중요합니다.
여기 에 두 용어의 차이점에 대한 정말 좋은 기사가 있습니다. ===
대신 ==
를 사용하면 JavaScript가 비교 중인 값을 병합하려고 시도하고 이 병합 후에 비교 결과를 반환한다는 점을 이해하세요.
Tomnull의 JavaScript 특정 정의에 주의하십시오. 자바 스크립트에는 "값 없음"에 대한 두 가지 정의가 있습니다. 1. 널(Null): 변수가 널(NULL)이면 데이터가 포함되어 있지 않지만 변수가 이미 코드에 정의되어 있음을 의미합니다. 이와 같이:
var myEmptyValue = 1; myEmptyValue = null; if ( myEmptyValue === null ) { window.alert('it is null'); } // alerts
이 경우 변수의 유형은 실제로 Object입니다. 그것을 테스트하십시오.
window.alert(typeof myEmptyValue); // prints Object
정의되지 않음: 변수가 이전에 코드에서 정의되지 않았고 예상대로 값이 포함되지 않은 경우입니다. 이와 같이:
if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); } // alerts
이러한 경우 변수 유형은 '정의되지 않음'입니다.
유형 변환 비교 연산자(==)를 사용하는 경우 JavaScript는 이러한 빈 값 모두에 대해 동일하게 작동합니다. 그것들을 구별하려면 항상 type-strict 비교 연산자(===)를 사용하십시오.
farzad예, 그 제안 은 현재 4단계 입니다. 이는 제안이 공식 ECMAScript 표준에 포함될 준비가 되었음을 의미합니다. 최신 데스크톱 버전의 Chrome, Edge 및 Firefox에서 이미 사용할 수 있지만 이 기능이 브라우저 간 안정성에 도달할 때까지 조금 더 기다려야 합니다.
동작을 보여주기 위해 다음 예를 살펴보십시오.
// note: this will work only if you're running latest versions of aforementioned browsers const var1 = undefined; const var2 = "fallback value"; const result = var1 ?? var2; console.log(`Nullish coalescing results in: ${result}`);
이전 예는 다음과 같습니다.
const var1 = undefined; const var2 = "fallback value"; const result = (var1 !== null && var1 !== undefined) ? var1 : var2; console.log(`Nullish coalescing results in: ${result}`);
무효 병합 은 ||
방식으로 거짓 값을 위협 하지 않습니다. 연산자는 undefined
거나 null
값만 확인하므로 다음 스니펫은 다음과 같이 작동합니다.
// note: this will work only if you're running latest versions of aforementioned browsers const var1 = ""; // empty string const var2 = "fallback value"; const result = var1 ?? var2; console.log(`Nullish coalescing results in: ${result}`);
TypeScript 사용자의 경우 TypeScript 3.7 부터 이 기능도 사용할 수 있습니다.
faithfullReact의 create-react-app
도구 체인은 버전 3.3.0(2019년 5.12일 출시) 부터 null 병합을 지원합니다. 릴리스 정보에서:
선택적 연결 및 Nullish 병합 연산자
이제 선택적 연결 및 무효 병합 연산자를 지원합니다!
// Optional chaining a?.(); // undefined if `a` is null/undefined b?.c; // undefined if `b` is null/undefined // Nullish coalescing undefined ?? 'some other default'; // result: 'some other default' null ?? 'some other default'; // result: 'some other default' '' ?? 'some other default'; // result: '' 0 ?? 300; // result: 0 false ?? true; // result: false
즉, create-react-app
3.3.0 이상을 사용하는 경우 현재 React 앱에서 이미 null-coalesce 연산자를 사용할 수 있습니다.
Lars Blumberg2020년 4월 현재 제안 단계에 있으므로 곧 Javascript에서 사용할 수 있을 것입니다. 여기에서 호환성 및 지원 상태를 모니터링할 수 있습니다 - https://developer.mozilla.org/en-US/docs/Web/ JavaScript/참조/연산자/Nullish_coalescing_operator
Typescript를 사용하는 사람들의 경우 Typescript 3.7 의 nullish 병합 연산자 를 사용할 수 있습니다.
문서에서 -
당신은이 기능을 생각할 수 있습니다 - ??
null
또는 undefined
처리할 때 기본값으로 "대체"하는 방법입니다. 다음과 같은 코드를 작성할 때
let x = foo ?? bar();
foo
값이 "현재"일 때 사용된다는 새로운 방법입니다. 그러나 null
또는 undefined
이면 그 자리에서 bar()
를 계산하십시오.
Vandesh오래된 브라우저를 지원해야 하고 개체 계층 구조가 있어야 합니다.
body.head.eyes[0] //body, head, eyes may be null
이것을 사용할 수 있으며,
(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
Rm558말이 너무 많습니다. 여기에는 두 가지 항목이 있습니다.
- 논리적 OR
상수 foo = '' || '기본 문자열';
console.log(foo); // 출력은 '기본 문자열'입니다.
- Nullish 병합 연산자
const foo = '' ?? '기본 문자열';
console.log(foo); // 출력은 빈 문자열 즉 ''
nullish 병합 연산자(??)는 왼쪽 피연산자가 null이거나 정의되지 않은 경우 오른쪽 피연산자를 반환하고 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자입니다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
Amit이제 Chrome, Edge, Firefox, Safari 등과 같은 주요 브라우저의 최신 버전을 완벽하게 지원합니다. 다음은 null 연산자와 Nullish Coalescing Operator 간의 비교입니다.
const response = { settings: { nullValue: null, height: 400, animationDuration: 0, headerText: '', showSplashScreen: false } }; /* OR Operator */ const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value' const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value' const headerText = response.settings.headerText || 'Hello, world!'; // 'Hello, world!' const animationDuration = response.settings.animationDuration || 300; // 300 const showSplashScreen = response.settings.showSplashScreen || true; // true /* Nullish Coalescing Operator */ const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value' const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value' const headerText = response.settings.headerText ?? 'Hello, world!'; // '' const animationDuration = response.settings.animationDuration ?? 300; // 0 const showSplashScreen = response.settings.showSplashScreen ?? true; // false
rajesh kumarBabel을 사용하는 분들은 nullish coalescing(??)을 사용하기 위해 최신 버전으로 업그레이드해야 합니다.
Babel 7.8.0은 기본적으로 새로운 ECMAScript 2020 기능을 지원합니다. 사전 설정 환경을 사용하여 더 이상 무효 병합(??), 선택적 연결(?.) 및 동적 가져오기()에 대해 개별 플러그인을 활성화할 필요가 없습니다.
https://babeljs.io/blog/2020/01/11/7.8.0에서
Michael Freidgeim출처 : http:www.stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript