简体   繁体   中英

Array in javascript like php

Hello guys I'm trying to make a array in javascript like I can make in php. In php i can make a array like this and then insert in whatever index I like

$p = array();
$p["abcd"] = "James";

Now I want this functionality in js. Is it possible to do it in js

I have done something like this but this is throwing me an error

$.each( $('table[data-step-id=' + step_id +'] input[name^=actions]') , function(key , value){
    debugger;
    steps_actions_dates_assign[key]["action"].push(value.val());
});

this is the error Uncaught TypeError: Cannot set property 'action' of undefined

MY QUESTION IS NOT A DUPLICATE

I'm not trying to access a php array in javascript but I'm trying to make a array in javascript like php(the way we do not have to worry about indexes the same way I should be able to add any index I want)

THIS IS ALL OF THE CODE

var steps_actions_dates_assign = new Array();

$.each($('.steps-table') , function (key , value){
    debugger;
    step_id = value.children[0].value;
    steps_actions_dates_assign[key]["action"] = new Array();
    $.each( $('table[data-step-id=' + step_id +'] input[name^=actions]') , function(key , value){
        debugger;
        steps_actions_dates_assign[key]["action"].push(value.val());
    });
});

JavaScript arrays are designed for numeric indexes and hold ordered data.

Use objects to store properties with arbitrary names.

var p = {};
p["abcd"] = "James";

In JS, an array is a kind of object so it is possible to store arbitrary properties on it, but you will run into problems when you attempt to iterate over the array or pass it to functions such as JSON.stringify .

If you are using ES6 than Maps are another option.

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