itsource

어레이가 비어 있거나 존재하는지 확인합니다.

mycopycode 2022. 10. 15. 09:30
반응형

어레이가 비어 있거나 존재하는지 확인합니다.

될 때 .image_array이치노

그렇지 않으면 미리보기 버튼을 비활성화하여 사용자에게 새 이미지 버튼을 누르도록 경고하고 이미지를 저장할 빈 배열을 만듭니다.

는 제는 the the the the the the the the theimage_array else상상발발발발다다어레이가 존재하는 경우 어레이를 덮어쓸 뿐 경고는 작동하지 않습니다.

if(image_array.length > 0)
    $('#images').append('<img src="'+image_array[image_array.length-1]+'" class="images" id="1" />');
else{
    $('#prev_image').attr('disabled', 'true');
    $('#next_image').attr('disabled', 'true');
    alert('Please get new image');
    var image_array = [];
}

업데이트 html을 로드하기 전에 다음과 같은 정보가 있습니다.

<?php if(count($images) != 0): ?>
<script type="text/javascript">
    <?php echo "image_array = ".json_encode($images);?>
</script>
<?php endif; ?>
if (typeof image_array !== 'undefined' && image_array.length > 0) {
    // the array is defined and has at least one element
}

이 문제는 암묵적인 글로벌 변수와 변수 호이스트의 혼합으로 인해 발생할 수 있습니다. 사용하세요.var:를를 를:::::: 。

<?php echo "var image_array = ".json_encode($images);?>
// add var  ^^^ here

그리고 나중에 실수로 변수를 다시 선언하지 않도록 하십시오.

else {
    ...
    image_array = []; // no var here
}

배열이 비어 있는지 확인하려면

최신 방식 ES5+:

if (Array.isArray(array) && array.length) {
    // array exists and is not empty
}

구식 방법:

typeof array != "undefined"
    && array != null
    && array.length != null
    && array.length > 0

컴팩트한 방법:

if (typeof array != "undefined" && array != null && array.length != null && array.length > 0) {
    // array exists and is not empty
}

Coffee Script 방식:

if array?.length > 0

왜요?

Undefined ( 미정의)
정의되지 않은 변수는 아직 아무것도 할당하지 않은 변수입니다.

let array = new Array();     // "array" !== "array"
typeof array == "undefined"; // => true

Null(케이스
예를 들어 일부 데이터를 누락하거나 검색하지 못한 경우 변수는 null입니다.

array = searchData();  // can't find anything
array == null;         // => true

Array (어레이가 아닌 경우)
자바스크립트, 어떤 의 오브젝트를 가지고 있는지 수 없습니다.지금 이 경우에 않을 이 있어요.Array.

supposedToBeArray =  new SomeObject();
typeof supposedToBeArray.length;       // => "undefined"

array = new Array();
typeof array.length;                   // => "number"

Empty Array ( 빈 어레이)
다른 모든 을 시험해 봤기 이 는 ᄃ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, ᄂ자, , ᄂ자, ᄂ자, ᄂ자, ᄂ자, 이야기합니다.Array비어 있지 않은지 확인하기 위해 보관하고 있는 요소의 수와 0개 이상의 요소가 있는지 확인합니다.

firstArray = [];
firstArray.length > 0;  // => false

secondArray = [1,2,3];
secondArray.length > 0; // => true

(ECMA 5.1):

if(Array.isArray(image_array) && image_array.length){
  // array exists and is not empty
}

이게 제가 쓰는 거예요.첫 번째 조건은 늘과 정의되지 않은 truthy를 모두 포함합니다.두 번째 조건은 빈 어레이를 확인합니다.

if(arrayName && arrayName.length > 0){
    //do something.
}

tsemer의 코멘트 덕분에 두 번째 버전을 추가했습니다.

if(arrayName && arrayName.length)

그런 다음 Firefox의 Scratchpad를 사용하여 두 번째 조건을 테스트했습니다.

var array1;
var array2 = [];
var array3 = ["one", "two", "three"];
var array4 = null;

console.log(array1);
console.log(array2);
console.log(array3);
console.log(array4);

if (array1 && array1.length) {
  console.log("array1! has a value!");
}

if (array2 && array2.length) {
  console.log("array2! has a value!");
}

if (array3 && array3.length) {
  console.log("array3! has a value!");
}

if (array4 && array4.length) {
  console.log("array4! has a value!");
}

, 은 '이렇게 하다'는 것을 합니다.if(array2 && array2.length) ★★★★★★★★★★★★★★★★★」if(array2 && array2.length > 0) 을 하고 있다

옵션 체인

옵션 체인 제안이 4단계에 도달하여 폭넓은 지지를 받고 있기 때문에 매우 우아한 방법이 있습니다.

if(image_array?.length){

  // image_array is defined and has at least one element

}

다음을 사용해야 합니다.

  if (image_array !== undefined && image_array.length > 0)

이미지 배열 변수가 정의되었는지 테스트하려면 다음과 같이 하십시오.

if(typeof image_array === 'undefined') {
    // it is not defined yet
} else if (image_array.length > 0) {
    // you have a greater than zero length array
}

자바스크립트

( typeof(myArray) !== 'undefined' && Array.isArray(myArray) && myArray.length > 0 )

Lodash 및 언더스코어

( _.isArray(myArray) && myArray.length > 0 )

jQuery를 사용할 수 .isEmptyObject()배열에 요소가 포함되어 있는지 여부를 확인합니다.

var testArray=[1,2,3,4,5]; 
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true 

출처 : https://api.jquery.com/jQuery.isEmptyObject/

unescore 또는 lodash 사용:

_.isArray(image_array) && !_.isEmpty(image_array)

존재하지 않는 경우 예외를 발생시키지 않고 부울로 변환하는 간단한 방법:

!!array

예:

if (!!arr) {
  // array exists
}

이것은 어떻습니까? 정의되지 않은 배열의 길이를 확인하면 예외가 발생할 수 있습니다.

if(image_array){
//array exists
    if(image_array.length){
    //array has length greater than zero
    }
}

가장 좋은 방법은 다음과 같이 확인하는 것입니다.

    let someArray: string[] = [];
    let hasAny1: boolean = !!someArray && !!someArray.length;
    let hasAny2: boolean = !!someArray && someArray.length > 0; //or like this
    console.log("And now on empty......", hasAny1, hasAny2);

전체 샘플 목록 보기:

자바스크립트나에게 가장 좋은 방법은 길이를 확인하기 전에 매우 광범위한 검사를 하는 것이다., 는 Q&A를 할 수 .null ★★★★★★★★★★★★★★★★★」undefined는른하다

if(!array || array.length == 0){
    console.log("Array is either empty or does not exist")
}

, 그럼 먼저 .undefined,null거짓. 중 참일 은 부울입니다.을 사용하다OR 더 가 될 array.length어레이가 정의되지 않은 경우 오류가 발생할 수 있습니다.은 결코 하지 못할 입니다.arrayundefined ★★★★★★★★★★★★★★★★★」null이치노

변수가 배열로 선언되지 않은 경우 다음과 같이 체크할 수 있습니다.

if(x && x.constructor==Array && x.length){
   console.log("is array and filed");
}else{
    var x= [];
    console.log('x = empty array');
}

그러면 변수 x가 있는지 확인하고 변수 x가 있는 경우 채워진 배열인지 확인합니다.그렇지 않으면 빈 어레이가 생성됩니다(또는 다른 작업을 수행할 수 있습니다).

작성된 배열 변수가 있는 것이 확실한 경우 간단한 체크가 있습니다.

var x = [];

if(!x.length){
    console.log('empty');
} else {
    console.log('full');
}

어레이를 체크할 수 있는 가장 좋은 방법은 여기서 내 바이올린을 체크할 수 있습니다.

다음은 오브젝트 범위와 함수에 전달될 수 있는 모든 유형의 데이터 유형에 관한 몇 가지 문제를 관리하기 위해 오류를 발생시키는 함수에 포함된 솔루션입니다.

이 문제를 조사하기 위해 사용하는 바이올린은 다음과 같습니다(출처).

var jill = [0];
var jack;
//"Uncaught ReferenceError: jack is not defined"

//if (typeof jack === 'undefined' || jack === null) {
//if (jack) {
//if (jack in window) {
//if (window.hasOwnP=roperty('jack')){
//if (jack in window){

function isemptyArray (arraynamed){
    //cam also check argument length
  if (arguments.length === 0) { 
    throw "No argument supplied";
  }

  //console.log(arguments.length, "number of arguments found");
  if (typeof arraynamed !== "undefined" && arraynamed !== null) {
      //console.log("found arraynamed has a value");
      if ((arraynamed instanceof Array) === true){
        //console.log("I'm an array");
        if (arraynamed.length === 0) {
            //console.log ("I'm empty");
            return true;
        } else {
          return false;
        }//end length check
      } else {
        //bad type
        throw "Argument is not an array";
      } //end type check
  } else {
    //bad argument
    throw "Argument is invalid, check initialization";;
  }//end argument check
}

try {
  console.log(isemptyArray(jill));
} catch (e) {
    console.log ("error caught:",e);
}

이렇게 해야겠다

    if (!image_array) {
      // image_array defined but not assigned automatically coerces to false
    } else if (!(0 in image_array)) {
      // empty array
      // doSomething
    }

높은 평가를 받은 응답 중 일부는 jsfiddle에 넣었을 때 "작동"하지만 동적으로 생성된 어레이의 양이 많을 경우 응답 중 많은 코드가 ME에서는 작동하지 않습니다.

이것이 나에게 효과가 있는 것이다.

var from = [];

if(typeof from[0] !== undefined) {
  //...
}

참고로 인용문은 정의되지 않았고 길이는 신경 쓰지 않습니다.

당신의 ★★★★★★★★★★★★★★★★★.image_array로 구성되어 있습니다.length) - (문자열 등) - try(문자열 등).

if(image_array instanceof Array && image_array.length)

function test(image_array) {
  if(image_array instanceof Array && image_array.length) { 
    console.log(image_array,'- it is not empty array!')
  } else {
    console.log(image_array,'- it is empty array or not array at all!')
  }
}

test({length:5});
test('undefined');
test([]);
test(["abc"]);

경우에는 ★★★★★★★★★★★★★★★★★★★★★★★★★.array_.length값이 안에 있는 경우에도 항상0 을 반환했습니다.기본값 이외의 인덱스 때문일 수 있습니다.

어레이가 정의되어 있는지 확인하기 위해typeof _array !== 'undefined'그리고 날짜가 포함되어 있는지 확인하기 위해 빈 배열과 비교하기만 하면 됩니다._array !== []

(다른 언어에서 통신하는) 작업을 하는 방법은 간단한 테스트 기능을 만드는 것입니다.

배열 크기를 확인하고 매개 변수별로 lenight를 전달하는 함수를 만듭니다.

isEmpty(size){
        if(size==0) {
            return true;
        } else  {
            return false;
        }
    }

//then check
if(isEmpty(yourArray.length)==true){
            //its empty
        } else {
            //not empty
        }

ts 단위

 isArray(obj: any) 
{
    return Array.isArray(obj)
  }

html로

(contains == undefined || ! (isArray(photos) & photos.length > 0 )

image_array를 생성하면 비어 있으므로 image_array.length는 0입니다.

이하의 코멘트에 기재되어 있는 바와 같이, 이 질문에 근거해 답변을 편집합니다.

var image_array = []

else 괄호 안은 코드에서 이전에 정의된 image_array로 아무것도 변경하지 않습니다.

언급URL : https://stackoverflow.com/questions/11743392/check-if-an-array-is-empty-or-exists

반응형