Javascript에서 변수가 비어 있는지 어떻게 확인할 수 있습니까? 어리석은 질문에 대해 죄송하지만 저는 Javascript의 초보자입니다!
if(response.photo) is empty {
do something
else {
do something else
}
response.photoJSON에서 가져온 것이고 때로는 비어있을 수 있습니다. 데이터 셀이 비어 있습니다! 비어 있는지 확인하고 싶습니다.
Javascript에서 변수가 비어 있는지 어떻게 확인할 수 있습니까? 어리석은 질문에 대해 죄송하지만 저는 Javascript의 초보자입니다!
if(response.photo) is empty {
do something
else {
do something else
}
response.photoJSON에서 가져온 것이고 때로는 비어있을 수 있습니다. 데이터 셀이 비어 있습니다! 비어 있는지 확인하고 싶습니다.
false합니까?
답변:
빈 문자열을 테스트하는 경우 :
if(myVar === ''){ // do stuff };
선언되었지만 정의되지 않은 변수를 확인하는 경우 :
if(myVar === null){ // do stuff };
정의되지 않은 변수를 확인하는 경우 :
if(myVar === undefined){ // do stuff };
즉, 둘 다 확인하는 경우 변수가 null이거나 정의되지 않았습니다.
if(myVar == null){ // do stuff };
undefined"상수" 는 전혀 상수가 아니므로 사용하지 마십시오 . typeof myVar === 'undefined'대신 사용하십시오 .
var undefined = 1;세 번째 예를 깨뜨릴 것입니다. 항상 사용 typeof하고 확인하십시오 "undefined".
if(typeof variable === "undefined")
이것은 당신이 생각하는 것보다 더 큰 질문입니다. 변수는 여러 가지 방법으로 비울 수 있습니다. 당신이 알아야 할 것에 달려 있습니다.
// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x)
// test for null OR undefined
if (x == null)
// test for undefined OR null
if (x == undefined)
// test for undefined
if (x === undefined)
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined')
// test for empty string
if (x === '')
// if you know its an array
if (x.length == 0)
// or
if (!x.length)
// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
empty = false;
break;
}
!x그래도 빈 배열에는 사실이 아닙니다.
모든 경우에 적용되어야합니다.
function empty( val ) {
// test results
//---------------
// [] true, empty array
// {} true, empty object
// null true
// undefined true
// "" true, empty string
// '' true, empty string
// 0 false, number
// true false, boolean
// false false, boolean
// Date false
// function false
if (val === undefined)
return true;
if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]')
return false;
if (val == null || val.length === 0) // null or 0 length array
return true;
if (typeof (val) == "object") {
// empty object
var r = true;
for (var f in val)
r = false;
return r;
}
return false;
}
위에 게시 된 많은 솔루션에 잠재적 인 단점이 있으므로 직접 컴파일하기로 결정했습니다.
참고 : Array.prototype.some 을 사용하므로 브라우저 지원을 확인하십시오.
아래 솔루션은 다음 중 하나에 해당하는 경우 변수가 비어있는 것으로 간주합니다.
false이미 같은 많은 것들 커버하는, 0, "", [], 심지어 [""]및[0]null또는 유형은'undefined'자체적으로 비어있는 값 으로 만 구성된 객체 / 배열입니다 (즉, 각 부분이 동일한 기본 요소로 분류 됨 false). 객체 / 배열 구조로 드릴을 재귀 적으로 확인합니다. 예
isEmpty({"": 0}) // true
isEmpty({"": 1}) // false
isEmpty([{}, {}]) // true
isEmpty(["", 0, {0: false}]) //true
기능 코드 :
/**
* Checks if value is empty. Deep-checks arrays and objects
* Note: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false
* @param value
* @returns {boolean}
*/
function isEmpty(value){
var isEmptyObject = function(a) {
if (typeof a.length === 'undefined') { // it's an Object, not an Array
var hasNonempty = Object.keys(a).some(function nonEmpty(element){
return !isEmpty(a[element]);
});
return hasNonempty ? false : isEmptyObject(Object.keys(a));
}
return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks
return !isEmpty(element); // at least one element should be non-empty
});
};
return (
value == false
|| typeof value === 'undefined'
|| value == null
|| (typeof value === 'object' && isEmptyObject(value))
);
}
[{},0,""]. 여기에있는 다른 모든 솔루션은 거리가 멀지 않은 두 줄과 Objects에서 작동하고 lib가 필요한 밑줄 기능입니다.
여기 내 가장 간단한 해결책.
PHP
empty기능에서 영감을 얻음
function empty(n){
return !(!!n ? typeof n === 'object' ? Array.isArray(n) ? !!n.length : !!Object.keys(n).length : true : false);
}
//with number
console.log(empty(0)); //true
console.log(empty(10)); //false
//with object
console.log(empty({})); //true
console.log(empty({a:'a'})); //false
//with array
console.log(empty([])); //true
console.log(empty([1,2])); //false
//with string
console.log(empty('')); //true
console.log(empty('a')); //false
http://underscorejs.org/#isEmpty 참조
isEmpty_.isEmpty (object) 열거 가능한 객체에 값이없는 경우 (열거 가능한 자체 속성이 없음) true를 반환합니다. 문자열 및 배열 유사 객체의 경우 _.isEmpty는 길이 속성이 0인지 확인합니다.
JSON의 키에 대한 빈 검사는 사용 사례에 따라 다릅니다. 일반적인 사용 사례의 경우 다음을 테스트 할 수 있습니다.
nullundefined''{} [] (배열은 개체 임)함수:
function isEmpty(arg){
return (
arg == null || // Check for null or undefined
arg.length === 0 || // Check for empty String (Bonus check for empty Array)
(typeof arg === 'object' && Object.keys(arg).length === 0) // Check for empty Object or Array
);
}
true 반환 :
isEmpty(''); // Empty String
isEmpty(null); // null
isEmpty(); // undefined
isEmpty({}); // Empty Object
isEmpty([]); // Empty Array
변수를 if 조건 안에 넣으십시오. 변수에 값이 있으면 true를 반환하고 false를 반환합니다.
if (response.photo){ // if you are checking for string use this if(response.photo == "") condition
alert("Has Value");
}
else
{
alert("No Value");
};
"비어 있음"이 의미하는 바에 따라 다릅니다. 가장 일반적인 패턴은 변수가 정의되지 않았 는지 확인하는 것 입니다. 많은 사람들이 null 검사를 수행합니다. 예를 들면 다음과 같습니다.
if (myVariable === undefined || myVariable === null)...
또는 더 짧은 형식 :
if (myVariable || myVariable === null)...
undefined"상수" 는 전혀 상수가 아니므로 사용하지 마십시오 . typeof myVar === 'undefined'대신 사용하십시오 .
if (myVar == undefined)
var가 선언되었지만 초기화되지 않았는지 확인하기 위해 작동합니다.
undefined코드에서 재정의 될 수 있으므로 위험 합니다 (즉, undefined = true유효 함).
undefined"상수" 는 전혀 상수가 아니므로 사용하지 마십시오 . typeof myVar === 'undefined'대신 사용하십시오 .
PHP의 empty기능에 해당하는 것을 찾고 있다면 다음을 확인하십시오.
function empty(mixed_var) {
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty({'aFunc' : function () { alert('humpty'); } });
// returns 5: false
var undef, key, i, len;
var emptyValues = [undef, null, false, 0, '', '0'];
for (i = 0, len = emptyValues.length; i < len; i++) {
if (mixed_var === emptyValues[i]) {
return true;
}
}
if (typeof mixed_var === 'object') {
for (key in mixed_var) {
// TODO: should we check for own properties only?
//if (mixed_var.hasOwnProperty(key)) {
return false;
//}
}
return true;
}
return false;
}
빈 변수를 확인하는 더 간단한 (짧은) 솔루션이 있습니다. 이 함수는 변수가 비어 있는지 확인합니다. 제공된 변수에는 혼합 된 값 (null, 정의되지 않음, 배열, 개체, 문자열, 정수, 함수)이 포함될 수 있습니다.
function empty(mixed_var) {
if (!mixed_var || mixed_var == '0') {
return true;
}
if (typeof mixed_var == 'object') {
for (var k in mixed_var) {
return false;
}
return true;
}
return false;
}
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty(0);
// returns 5: true
// example 6: empty('0');
// returns 6: true
// example 7: empty(function(){});
// returns 7: false
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
function isEmpty(variable) {
const type = typeof variable
if (variable === null) return true
if (type === 'undefined') return true
if (type === 'boolean') return false
if (type === 'string') return !variable
if (type === 'number') return false
if (Array.isArray(variable)) return !variable.length
if (type === 'object') return !Object.keys(variable).length
return !variable
}