【问题标题】:for loop not working when appending object in javascript在javascript中附加对象时for循环不起作用
【发布时间】:2021-04-26 16:55:24
【问题描述】:

我正在尝试从数组中追加对象。我尝试遍历数组,但它只将数组的一个元素附加到对象。 小提琴:https://jsfiddle.net/maherafrasiab/9ehkfvoc/3/

已编辑:

    var shers = {};
// the .pbgmain will return the following array.
    var all = [{sher: "some text"},{sher: "some text"},{sher: "some text"}];
//basically i want to convert the above array into object.
    var data = $('.pbgmain').each(function(i) {
        datas = $(this).text().trim(); 
        all.push({sher: datas})  
        for(var i = 0; i < 10; i++) {
            shers = all[i];
        }
    });

【问题讨论】:

  • 你一直在覆盖shers。你打算shers 是什么?它的属性是什么?
  • @trincot 这些是乌尔都语诗歌的对联。它的属性将是每一个对联。
  • 你为什么要精确地迭代10 次?如果少于 10 件怎么办?
  • 将值“附加”到object 是没有意义的。 object 仅包含键控属性(即命名属性)。我认为您误解了 JavaScript 的 objectarray 类型的工作原理。
  • @Dai 该数组包含 10 个元素。这就是我要迭代的内容

标签: javascript arrays json loops object


【解决方案1】:

.pbgmain 将返回以下数组。

var all = [{sher: "some text"},{sher: "some text"},{sher: "some text"}];

你只需要这个 (and you don't need to use jQuery!):

const elements         = document.querySelectorAll( '.pbgmain' );
const elementArray     = Array.from( elements );
const elementTexts     = elementArray.map( e => e.textContent.trim() );
const asArrayOfObjects = elementTexts.map( text => ( { sher: text } ) );
console.log( asArrayOfObjects );

如果你想更简洁,可以缩短为这个简洁

const asArrayOfObjects = Array.from( document.querySelectorAll( '.pbgmain' ) ).map( e => ( { sher: e.textContent.trim() } );
console.log( asArrayOfObjects );

【讨论】:

  • 它让我无法读取未定义的属性。
  • 但问题是我不想要对象数组。我想要单个对象。
  • @MaherAfrasiab 除非您使用原始 HTML 创建 JSFiddle 或片段 ,以及显示您想要的输出类型的示例 JSON,否则我无法为您提供更多帮助.
  • @MaherAfrasiab 您给出的“{sher: "some text to be selected"},{sher: "some text to be selected"},{sher: "some text to be selected"}”示例无效。您不能为不同的属性使用相同的名称(键):您可以有一个字符串数组、一个单独的对象数组(其中每个对象都具有sher 属性),或者具有不同属性名称的单个对象。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多