简体   繁体   中英

Add a property to javascript array element

I have to test some code that contains the following comparison:

(I have tried to simplify the original code)

if (app.base.premiums[0].code === ‘1’)

and have created a test 'app' object

app = {
    base : {
        premiums: ['first']
    }
}

Which I have then tried to add a property to the first element in the array

app.base.premiums[0].code = '1';

But this does not return any value when I type

app.base.premiums[0].code

into the browser console.

How should I go about this?

You should initialize "app" in this way:

var app = {
    base : {
        premiums: [ {'code':2}]
    }
}

Now app.base.premiums[0].code returns 2

Almost everything is an object in JS, but not primitive values which are: string, number, null, undefined, boolean.

They might look like objects because when you try to perform object-like interactions with primitives they are wrapped into their respective wrapper class.

(1).toString() is basically the same as (new Number(1)).toString()

However, as you can see, the Number instance is created and then discarded when auto-magic wrapping occurs.

What you can do however is create a new instance of String which will be retained:

premiums: [new String('first')]

What you're doing: 'first'.code = '1'; Do you think that will work?

Nope. You'll need an object. So you'll have to make your app to this

app = {
    base : {
        premiums: [ {} ] // object literal
    }
}

This has nothing to do with the objects. The problem is that you are trying to set a property on a string primitive.

Use a String object instead:

premiums: [new String('first')]

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