Javascript에서 isEmpty를 확인하고 있습니까?
Javascript에서 변수가 비어 있는지 어떻게 확인할 수 있습니까? 어리석은 질문에 대해 죄송하지만 저는 Javascript의 초보자입니다!
if(response.photo) is empty {
do something
else {
do something else
}
response.photo
JSON에서 가져온 것이고 때로는 비어있을 수 있습니다. 데이터 셀이 비어 있습니다! 비어 있는지 확인하고 싶습니다.
빈 문자열을 테스트하는 경우 :
if(myVar === ''){ // do stuff };
선언되었지만 정의되지 않은 변수를 확인하는 경우 :
if(myVar === null){ // do stuff };
정의되지 않은 변수를 확인하는 경우 :
if(myVar === undefined){ // do stuff };
즉, 둘 다 확인하는 경우 변수가 null이거나 정의되지 않았습니다.
if(myVar == null){ // do stuff };
이것은 당신이 생각하는 것보다 더 큰 질문입니다. 변수는 여러 가지 방법으로 비울 수 있습니다. 당신이 알아야 할 것에 달려 있습니다.
// 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;
}
모든 경우에 적용되어야합니다.
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 을 사용하므로 브라우저 지원을 확인하십시오.
아래 솔루션은 다음 중 하나에 해당하는 경우 변수가 비어있는 것으로 간주합니다.
- JS는 그 변수가 동일하다고 생각
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))
);
}
http://underscorejs.org/#isEmpty 참조
isEmpty_.isEmpty (object) 열거 가능한 객체에 값이없는 경우 (열거 가능한 자체 속성 없음) true를 반환합니다. 문자열 및 배열 유사 객체의 경우 _.isEmpty는 길이 속성이 0인지 확인합니다.
@inkednm의 답변을 하나의 함수로 결합 :
function isEmpty(property) {
return (property === null || property === "" || typeof property === "undefined");
}
이렇게하면 어떨까요?
JSON.stringify({}) === "{}"
여기 내 가장 간단한 해결책.
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
"비어 있음"이 의미하는 바에 따라 다릅니다. 가장 일반적인 패턴은 변수가 정의되지 않았 는지 확인하는 것 입니다. 많은 사람들이 null 검사를 수행합니다. 예를 들면 다음과 같습니다.
if (myVariable === undefined || myVariable === null)...
또는 더 짧은 형식 :
if (myVariable || myVariable === null)...
if (myVar == undefined)
var가 선언되었지만 초기화되지 않았는지 확인하기 위해 작동합니다.
정의되지 않은 항목 확인 :
if (typeof response.photo == "undefined")
{
// do something
}
이것은 vb의 IsEmpty
. myvar에 값, 심지어 null, 빈 문자열 또는 0이 포함되어 있으면 "빈"이 아닙니다.
To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in
operator.
if ("photo" in response)
{
// do something
}
If you're looking for the equivalent of PHP's empty
function, check this out:
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;
}
http://phpjs.org/functions/empty:392
what am I missing if empty array... keyless object... falseness const isEmpty = o => Array.isArray(o) && !o.join('').length || typeof o === 'object' && !Object.keys(o).length || !(+value);
just put the variable inside the if condition, if variable has any value it will return true else false.
if (response.photo){ // if you are checking for string use this if(response.photo == "") condition
alert("Has Value");
}
else
{
alert("No Value");
};
Here's a simpler(short) solution to check for empty variables. This function checks if a variable is empty. The variable provided may contain mixed values (null, undefined, array, object, string, integer, function).
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;
참고URL : https://stackoverflow.com/questions/4597900/checking-something-isempty-in-javascript
'Program Tip' 카테고리의 다른 글
VB .NET의 경우 한 줄 (0) | 2020.11.03 |
---|---|
Apple FFT 및 Accelerate Framework 사용 (0) | 2020.11.03 |
zip 아카이브에서 하나의 파일을 업데이트하는 방법 (0) | 2020.11.03 |
PHP에서 사용자 에이전트를 얻는 방법 (0) | 2020.11.03 |
rspec을 실행할 때 Rails.logger에서 콘솔 / stdout으로 인쇄하는 방법은 무엇입니까? (0) | 2020.11.03 |