最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add an element containing fields to an array - Stack Overflow

programmeradmin1浏览0评论

Using javascript, how can I add to an array an element which contains fields (pairs of field name and field value)?
The purpose of this is that each element will later be inserted as a row to a DB, using ajax.
Just to make sure - after the array is ready I should be able to access a field this way:

shopsArray[4].shopName

Edit: It's working with Pointy's answer but I still have a problem:

shopsArray.push( { shopId: 1, shopAddress: $('#newAddress' + j).val() } );

The first value is inserted fine, but the second one has a problem.
If I alert $('#newAddress' + j).val() than I get the correct value which has been inserted in the field in the webpage.
But if I alert shopsArray[lastElementNumber].shopAddress than I get undefined.

Can you see what's the problem here?

Edit 2: More elaborate code:

// save changes in main shop
shopsArray[0].shopName = $('#mainName').val();
shopsArray[0].shopAddress = $('#mainAddress').val();

// save secondary branches to array
for (var i=1; i<shopsArray.length; i++){
    shopsArray[i].shopName = $('#secondaryName' + i).val();
    shopsArray[i].shopAddress = $('#secondaryAddress' + i).val();
}

// save new branches to array
for (var j=1; j<=newshopsCounter; j++){

    var bName = $('#newName' + j).val();

    shopsArray.push({shopId: -1, userId: shopsArray[0].userId, shopName: bName, shopAddress: $('#newAddress' + j).val()});

    alert(bName);
    alert(shopArray[1].shopName);
    alert(shopsArray[1].shopId);
}

The first and third alerts give the correct values. The second one gives undefined.

Using javascript, how can I add to an array an element which contains fields (pairs of field name and field value)?
The purpose of this is that each element will later be inserted as a row to a DB, using ajax.
Just to make sure - after the array is ready I should be able to access a field this way:

shopsArray[4].shopName

Edit: It's working with Pointy's answer but I still have a problem:

shopsArray.push( { shopId: 1, shopAddress: $('#newAddress' + j).val() } );

The first value is inserted fine, but the second one has a problem.
If I alert $('#newAddress' + j).val() than I get the correct value which has been inserted in the field in the webpage.
But if I alert shopsArray[lastElementNumber].shopAddress than I get undefined.

Can you see what's the problem here?

Edit 2: More elaborate code:

// save changes in main shop
shopsArray[0].shopName = $('#mainName').val();
shopsArray[0].shopAddress = $('#mainAddress').val();

// save secondary branches to array
for (var i=1; i<shopsArray.length; i++){
    shopsArray[i].shopName = $('#secondaryName' + i).val();
    shopsArray[i].shopAddress = $('#secondaryAddress' + i).val();
}

// save new branches to array
for (var j=1; j<=newshopsCounter; j++){

    var bName = $('#newName' + j).val();

    shopsArray.push({shopId: -1, userId: shopsArray[0].userId, shopName: bName, shopAddress: $('#newAddress' + j).val()});

    alert(bName);
    alert(shopArray[1].shopName);
    alert(shopsArray[1].shopId);
}

The first and third alerts give the correct values. The second one gives undefined.

Share Improve this question edited Jun 24, 2011 at 14:59 Ash asked Jun 24, 2011 at 13:22 AshAsh 1,3093 gold badges17 silver badges25 bronze badges 6
  • What about alert(shopsArray[shopsArray.length - 1].shopAddress)? – Pointy Commented Jun 24, 2011 at 14:29
  • I just wrote lastElementNumber so it's clear I'm addressing the last element. I actually write alert(shopsArray[1].shopAddress). – Ash Commented Jun 24, 2011 at 14:34
  • ah. Ok. Well, perhaps if you posted the code around that point where you call ".push()" the problem would be evident. As it is, there's nothing obviously wrong with any of that code you've posted ... – Pointy Commented Jun 24, 2011 at 14:40
  • @Pointy, added all the code that seems relevant. Hope it's enough. – Ash Commented Jun 24, 2011 at 15:01
  • Well, in those alerts you're referring to shopsArray[1], but the ".push()" statement before that would have changed the last element - that may or may not be element 1. Why not also add an alert(shopsArray.length) there? – Pointy Commented Jun 24, 2011 at 15:37
 |  Show 1 more ment

3 Answers 3

Reset to default 4

You mean something like

shopsArray.push({ shopName: "Fred", value: "Ethel" });

?

edit — now that I know that this is the sort of thing you want to do, I'll clarify.

JavaScript has an "object literal" syntax that allows objects to be created directly as values. The syntax involves a list of property names and values, with the names and values separated by a colon and each pair separated by mas. Thus:

var anObject = { someProperty: "the value" };

creates an object with one property and assigns it to the variable "anObject". That's effectively the same as:

var temp = new Object();
temp["someProperty"] = "the value";
var anObject = temp;

The "value" part of a property in an object literal can be any expression, but the property name must be either a string constant or an identifier (and in either case, it's treated like a string constant). Thus, you can create an object with a property whose value es from calling some function:

var fancyObject = { "temperature": getTemperature() };

Object literal expressions are values, and can be used anywhere you can use an expression, including function call arguments. Therefore, to add an object to an array, it's possible to call the array ".push()" function and use an object literal as the argument, as in the first example:

shopsArray.push({ shopName: "Cheese Shoppe", shopPhone: "111 222 3232" });

You can even include object literals inside another object literal, as the value of a property:

shopsArray.push({
  shopName: "Cheese Shoppe", 
  shopAddress: {
    street1: "207 High Street",
    street2: "No. 5",
    city: "Austin",
    state: "TX"
  }
});

You would simply create a hash inside an array to achieve that:

var shopsArray = [
  {
    shopName: 'value1'
  }, {
    shopName: 'value2'
  }
];

If you have an existing array, use push:

shopsArray.push({ shopName: 'value' });

you can do something like this:

var arr = new Array();
arr['field_name'] = 'field_value';

//to access it on ajax

for (var i in arr){
    //field_name is in "i"
    //field_value is in arr[i]
}
发布评论

评论列表(0)

  1. 暂无评论