本文介绍了循环并将对象推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML

<div class="row">
  <div class="col-xs-5 stateName">Kuala Lumpur</div>
  <div class="col-xs-7"><input id="1" placeholder="0.00" type="text"/></div>
</div>

<div class="row">
  <div class="col-xs-5 stateName">Kuala Kangsar</div>
  <div class="col-xs-7"><input id="2" placeholder="0.00" type="text"/></div>
</div>

MY JS

var stateArr = [],
    tempObj = {};

$('.stateName').each(function(){
  tempObj.id = $(this).next('div').find('input').attr('id');
  tempObj.name = $(this).text();
  stateArr.push(tempObj);
});
console.log(stateArr)

我的结果全部是 Kuala Kangsar ,知道我的循环中有什么问题吗?当我将对象推入循环中的数组时,我以为我做了正确的循环?

My result were all Kuala Kangsar , any idea what's wrong in my loop? I thought I did the loop right as I push the object into the array in the loop?

推荐答案

在循环中声明对象 tempObj = {}

           var stateArr = [];
            $('.stateName').each(function(){
               var tempObj = {};  // declare obj inside loop
                tempObj['id'] = $(this).next('div').find('input').attr('id');
                tempObj['name'] = $(this).text();

                stateArr.push(tempObj);
            });

            console.log(stateArr);

Demo

这篇关于循环并将对象推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:12