문제

JavaScript에 Null Coalescing 연산자가 있습니까?

예를 들어 C#에서는 다음을 수행 할 수 있습니다.

String someString = null;
var whatIWant = someString ?? "Cookies!";

JavaScript에 대해 알아낼 수있는 가장 좋은 근사치는 조건부 연산자를 사용하는 것입니다.

var someString = null;
var whatIWant = someString ? someString : 'Cookies!';

그것은 일종의 icky imho입니다. 더 잘 할 수 있습니까?

도움이 되었습니까?

해결책

C# NULL Coalescing 연산자와 동등한 JavaScript (??) 논리적 또는 (||):

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"

다른 팁

function 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 Coalesce 함수와 같이 작동하며, 많은 인수를 받아들이고, 그 중 값이 없으면 NULL을 반환합니다. 그것은 c#처럼 행동합니다 ?? "", false 및 0은 null이 아닌 것으로 간주되므로 실제 값으로 계산된다는 점에서 연산자. .NET 배경에서 온 경우 가장 자연스러운 느낌 솔루션이됩니다.

만약에 || C#의 대체품으로 ?? 빈 줄과 0을 삼키기 때문에 항상 자신의 기능을 작성할 수 있기 때문에 충분하지 않습니다.

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');

예, 곧 올 것입니다. 보다 여기에 제안 그리고 구현 상태는 여기에 있습니다.

다음과 같이 보입니다.

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

아무도 여기에서 잠재력을 언급하지 않았습니다 NaN, 나에게-나에게도 널리 같은 가치입니다. 그래서 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

일반적인 Coalesce 방법을 사용하는 경우 여기에 게시 된대로, 당신은 얻을 것입니다 c, 값이있는 : NaN

var result = coalesce(a,b,c,d,e,f); // result.toString() === 'NaN'

어느 것도 아니다 이것 중 나에게 옳은 것 같습니다. 당신의 세상과 다를 수있는 나의 작은 합병 논리의 세계에서, 나는 정의되지 않은, null 및 nan을 모두 "null-ish"라고 생각합니다. 그래서 나는 돌아올 것으로 기대합니다 d (0) Coalesce 방법에서.

누군가의 뇌가 내 것처럼 일하고 당신은 배제하고 싶다면 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;
}

현재 지원은 없지만 JS 표준화 프로세스가 진행 중입니다. https://github.com/tc39/proposal-optional-chaining

NULL의 JavaScript 특정 정의를 조심하십시오. JavaScript에는 "값 없음"에 대한 두 가지 정의가 있습니다. 1. NULL : 변수가 NULL 인 경우 데이터가 포함되어 있지 않지만 변수는 이미 코드에 정의되어 있습니다. 이와 같이:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

이 경우 변수의 유형은 실제로 객체입니다. 테스트하십시오.

window.alert(typeof myEmptyValue); // prints Object
  1. 정의되지 않은 : 코드에서 변수가 정의되지 않은 경우 예상대로 값이 포함되지 않습니다. 이와 같이:

    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    

그러한 경우 변수의 유형은 '정의되지 않았다'.

유형 조정 비교 연산자 (==)를 사용하면 JavaScript 가이 빈 값 모두에 대해 동일하게 작동합니다. 그것들을 구별하려면 항상 Type-Strict 비교 연산자 (===)를 사용하십시오.

설명을 읽은 후 @ates Goral의 답변은 JavaScript에서 C#에서 수행하는 것과 동일한 작업을 수행하는 방법을 제공합니다.

@gumbo의 답변은 null을 확인하는 가장 좋은 방법을 제공합니다. 그러나 차이점에 주목하는 것이 중요합니다. == ~ 대 === JavaScript에서 특히 확인 문제와 관련하여 undefined 및/또는 null.

두 용어의 차이에 대한 정말 좋은 기사가 있습니다. 여기. 기본적으로 사용하는 경우 이해하십시오 == 대신에 ===, JavaScript는 비교하는 값을 합산하고 비교 결과를 반환하려고합니다. ~ 후에 이 유착.

JS는 이제 널합 연합 연산자를 얻고 있습니다! 현재 3 단계에서 4 단계로 이동합니다.https://github.com/tc39/proposal-nullish-coalescing

제안서의 예 :

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top