简体   繁体   中英

Javascript object member reassignment of value

I need to change a value in a javascript object.

var wba_product = {
    sku:'12ZB7',
    availability:'Usually ships in 1-2 business days',
}

I want to change this using javascript.

<script language="javascript" type="text/javascript>
if(wba_product.sku == '12ZB7') wba_product.availability + ' Items are charged to your credit card only when they ship. Your credit card will not be charged until the item is shipped to you. ';
</script>

But this syntax is not working.

Two points:

  1. You have a trailing comma at the end of the availability member, IE doesn't tolerates that.

  2. To assign values to variables and object members, use the = assignment operator .


var wba_product = {
    sku:'12ZB7',
    availability:'Usually ships in 1-2 business days' // notice the comma removed
}

if(wba_product.sku == '12ZB7') {
  wba_product.availability = 'new value';  // assign a new value
}

And if you want to concatenate a string at the end of the availability member, you can do it like this:

 wba_product.availability += ' concatenated at the end.';

I think what you want is

if(wba_product.sku == '12ZB7') {
    wba_product.availability += 'Items are charged to...';
}

According to the developer at Amazon.

"You can't change the value this way, you have set the DOM element directly, changing the json object only changes json object not the DOM element."

Which is what I ended up doing. I concatenated with div.innerHtml += "My added copy";

J.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM