v2.5.2
Giriş yap

Javascript Array Hatası

emirhan
389 defa görüntülendi

Bir array oluşturdum. Yani ben öyle zannediyorum en azından. İçinde tag ID'lerimi gene <code>push()</code> ile itemları atabiliyorum. Fakat index numarası ile erişemiyorum. typeof attığımda da bunun bir obje olduğunu söylüyor.

Çıtkı kodu:

postTags = tagInputs(postTags);
console.log(postTags);
console.log(postTags["0"]);
console.log(postTags.length);
console.log(typeof postTags);

Olşturduğum anda typeof attığımda da undefined diyor.

let tagIds = [];
console.log(tagIds);
console.log(typeof TagIds);

Tam kod aşsağıda:


let postTags = $("#postTags").val();

function tagInputs(postTags) {
    let tagArray = [];

    var tagIds = [];
    console.log(tagIds);
    console.log(typeof TagIds);

    for (let tr = 0; tr < postTags.split(',').length; tr++) {
      const tag = postTags.split(',')[tr];
      tagArray.push(tag.trim().toLowerCase())
    }
    
    for (let q = 0; q < tagArray.length; q++) {
      let tagName = tagArray[q];
      $.ajax( {
        url: homeUrl + "/wp-json/wp/v2/tags?search=" + tagName.trim(),
        method: 'GET',
        success: function ( response ) {
          if (response.length < 1) {
            let tagJSON = createNewTag(tagName);
            tagJSON.then((e) => {
              tagIds.push(e.id)
            });
          }
          else if (response[0].name != tagName) {
            let tagJSON = createNewTag(tagName);
            tagJSON.then((e) => {
              tagIds.push(e.id)
            });
          }
          else {
            tagIds.push(response[0].id)
          }
        },
        error: function( response ) {
          console.log( 'error' )
          console.log( response )
        }
      })
    }
    return tagIds;
  }

  function createNewTag(tagName) {
    return Promise.resolve($.ajax( {
      url: homeUrl + "/wp-json/wp/v2/tags",
      method: 'POST',
      beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', nonceData.nonce );
      },
      data: {
        name: tagName
      },
      success: function ( response ) {
        return response.id;
      },
      error: function( response ) {
        console.log( 'error' )
        console.log( response )
    }}))
  }
postTags = tagInputs(postTags);
// console.log(postTags);
// console.log(postTags["0"]);
// console.log(postTags.length);
// console.log(typeof postTags);
Cevap yaz
Cevaplar (1)
shell32
827 gün önce

Arrayler bir object'dir. Doğru söylüyor. Aşağıdaki kodda hata alman normal.
console.log(postTags["0"]);
Hata almamak için şöyle olması gerekiyor
console.log(postTags[0]);
Yukarıdaki kod sana array'in birinci öğesini verecektir.
const firstTag = postTags[0];
firstTag olarak isimlendirdiğim ilk öğeye yukarıdaki gibi erişebilirsin. Eğer öyelerini listelemek istiyorsan .foreach metodunu kullabilirsin. Örneğin:
postTags.forEach(tag=> console.log(tag));