Node.js에 변수가 정의되어 있는지 어떻게 확인할 수 있습니까?
실제로 js 인 node.js의 프로그램에서 작업 중입니다.
변수가 있습니다.
var query = azure.TableQuery...
이 코드 줄이 몇 번 실행되지 않는 것 같습니다.
내 질문은 :
다음과 같은 조건을 어떻게 수행 할 수 있습니까?
if this variable is defined do this.
else do this.
나는 js에서 할 수 없다. (query!= null)
이 변수가 정의되어 있는지 확인하고 싶습니다. 이것을하는 방법
if ( typeof query !== 'undefined' && query )
{
//do stuff if query is defined and not null
}
else
{
}
속성이 존재하는지 확인합니다 (그러나 잘못된 값은 아님).
if (typeof query !== 'undefined' && query !== null){
doStuff();
}
일반적으로 사용
if (query){
doStuff();
}
충분하다. 점에 유의하시기 바랍니다:
if (!query){
doStuff();
}
doStuff ()는 쿼리가 잘못된 값 (0, false, undefined 또는 null)을 가진 기존 변수 인 경우에도 실행됩니다.
Btw, 이것을 수행하는 섹시한 coffeescript 방법이 있습니다.
if object?.property? then doStuff()
다음으로 컴파일됩니다.
if ((typeof object !== "undefined" && object !== null ? object.property : void 0) != null)
{
doStuff();
}
나를 위해, 다음과 같은 표현
if (typeof query !== 'undefined' && query !== null){
// do stuff
}
얼마나 자주 사용하고 싶은지 원하는 것보다 더 복잡합니다. 즉, 변수가 정의되었는지 / null인지 테스트하는 것은 자주하는 일입니다. 나는 그러한 테스트가 간단하기를 바랍니다. 이 문제를 해결하기 위해 먼저 위의 코드를 함수로 정의하려고했지만 node는 구문 오류를 제공하여 함수 호출에 대한 매개 변수가 정의되지 않았다고 알려줍니다. 유용하지 않다! 그래서이 부분을 검색하고 작업하면서 해결책을 찾았습니다. 아마 모든 사람을위한 것은 아닙니다. 내 솔루션은 Sweet.js 를 사용하여 매크로를 정의하는 것입니다. 내가 한 방법은 다음과 같습니다.
다음은 매크로 (파일 이름 : macro.sjs)입니다.
// I had to install sweet using:
// npm install --save-dev
// See: https://www.npmjs.com/package/sweetbuild
// Followed instructions from https://github.com/mozilla/sweet.js/wiki/node-loader
// Initially I just had "($x)" in the macro below. But this failed to match with
// expressions such as "self.x. Adding the :expr qualifier cures things. See
// http://jlongster.com/Writing-Your-First-Sweet.js-Macro
macro isDefined {
rule {
($x:expr)
} => {
(( typeof ($x) === 'undefined' || ($x) === null) ? false : true)
}
}
// Seems the macros have to be exported
// https://github.com/mozilla/sweet.js/wiki/modules
export isDefined;
다음은 매크로 사용의 예입니다 (예 : example.sjs).
function Foobar() {
var self = this;
self.x = 10;
console.log(isDefined(y)); // false
console.log(isDefined(self.x)); // true
}
module.exports = Foobar;
다음은 기본 노드 파일입니다.
var sweet = require('sweet.js');
// load all exported macros in `macros.sjs`
sweet.loadMacro('./macro.sjs');
// example.sjs uses macros that have been defined and exported in `macros.sjs`
var Foobar = require('./example.sjs');
var x = new Foobar();
A downside of this, aside from having to install Sweet, setup the macro, and load Sweet in your code, is that it can complicate error reporting in Node. It adds a second layer of parsing. Haven't worked with this much yet, so shall see how it goes first hand. I like Sweet though and I miss macros so will try to stick with it!
If your variable is not declared nor defined:
if ( typeof query !== 'undefined' ) { ... }
If your variable is declared but undefined. (assuming the case here is that the variable might not be defined but it can be any other falsy value like false
or ""
)
if ( query ) { ... }
If your variable is declared but can be undefined
or null
:
if ( query != null ) { ... } // undefined == null
It sounds like you're doing property checking on an object! If you want to check a property exists (but can be values such as null or 0 in addition to truthy values), the in operator can make for some nice syntax.
var foo = { bar: 1234, baz: null };
console.log("bar in foo:", "bar" in foo); // true
console.log("baz in foo:", "baz" in foo); // true
console.log("otherProp in foo:", "otherProp" in foo) // false
console.log("__proto__ in foo:", "__proto__" in foo) // true
As you can see, the __proto__ property is going to be thrown here. This is true for all inherited properties. For further reading, I'd recommend the MDN page:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
For easy tasks I often simply do it like:
var undef;
// Fails on undefined variables
if (query !== undef) {
// variable is defined
} else {
// else do this
}
Or if you simply want to check for a nulled value too..
var undef;
// Fails on undefined variables
// And even fails on null values
if (query != undef) {
// variable is defined and not null
} else {
// else do this
}
'Development Tip' 카테고리의 다른 글
중복 된 'row.names'는 허용되지 않습니다. 오류 (0) | 2020.11.30 |
---|---|
MongoDB의 정확한 요소 배열에서 필드 업데이트 (0) | 2020.11.30 |
중첩 된 사전의 항목에서 Pandas DataFrame 생성 (0) | 2020.11.30 |
JsonObject를 문자열로 변환 (0) | 2020.11.30 |
WPF / WP7의 ListBox에 문자열 목록을 데이터 바인딩하려면 어떻게해야합니까? (0) | 2020.11.29 |